工厂方法
function User(){
const obj = new Object()
console.log(obj)
obj.name = 'gavin'
obj.showName = function(){
return obj.name
}
return obj
}
构造函数方法
function User(){
this.name = 'gavin'
this.showName = function(){
return this.name
}
}
原型方法
function User(){}
User.prototype.name = 'gavin'
User.prototype.showName = function(){
return this.name
}
以上三种方法都存在缺陷,在不使用es6的语法糖clss推荐以下
组合使用构造函数方法和原型方法
function User() {
this.name = 'gavin';
}
User.prototype.showName = function () {
return this.name;
};
const user1 = new User();
const user2 = new User();
console.log(user1);
console.log(user1.showName());
console.log(user1.showName === user2.showName);
从结果就可以看出,这种方式有自己的name,以及继承的方法,避免资源浪费。
es6定义类的方法
class User{
constructor(){
this.name = 'gavin'
}
showName(){
return this.name
}
}
babel转es5后还是很严格的考虑各种场景
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
var User = /*#__PURE__*/function () {
"use strict";
function User() {
_classCallCheck(this, User);
this.name = 'gavin';
}
_createClass(User, [{
key: "showName",
value: function showName() {
return this.name;
}
}]);
return User;
}();
扩展
- js的class语法糖果基本和java一直,都是一切皆对象嘛。
- c++的类的定义其实就是结构体的语法糖。
- 本质上都是堆内存的开辟。