JavaScript基础专题之创建对象几种方式及优缺点(九)
Opened this issue · 0 comments
前言
根据《JavaScript高级程序设计》(红宝书)来总结一下创建对象的几种方式及优缺点
1. 工厂模式
function createPerson(name) {
var o = new Object();
o.name = name;
o.getName = function () {
console.log(this.name);
};
return o;
}
var person1 = createPerson('chris');
缺点:对象无法识别,因为所有的实例都指向一个原型
2. 构造函数模式
function Person(name) {
this.name = name;
this.getName = function () {
console.log(this.name);
};
}
var person1 = new Person('chris');
缺点:每次创建实例时,每个方法都要被创建一次
3. 原型模式
function Person(name) {
}
Person.prototype.name = 'chris';
Person.prototype.getName = function () {
console.log(this.name);
};
var person1 = new Person();
缺点:1. 所有的属性和方法都共享 2. 不能初始化参数
3.1 原型模式优化
function Person(name) {
}
Person.prototype = {
name: 'chris',
getName: function () {
console.log(this.name);
}
};
var person1 = new Person();
缺点:重写了原型,丢失了constructor属性
3.2 原型模式优化
function Person(name) {
}
Person.prototype = {
constructor: Person,
name: 'chris',
getName: function () {
console.log(this.name);
}
};
var person1 = new Person();
优点:实例可以通过constructor属性找到所属构造函数
缺点:还是需要重写原型
4. 组合模式
构造函数模式与原型模式一起上
function Person(name) {
this.name = name;
}
Person.prototype = {
constructor: Person,
getName: function () {
console.log(this.name);
}
};
var person1 = new Person();
优点:该共享的共享,该私有的私有,使用最广泛的方式
缺点:有的人就是希望全部都写在一起,即更好的封装性
4.1 动态原型模式
function Person(name) {
this.name = name;
if (typeof this.getName != "function") {
Person.prototype.getName = function () {
console.log(this.name);
}
}
}
var person1 = new Person();
注意:使用动态原型模式时,不能用对象字面量重写原型
解释下为什么:
function Person(name) {
this.name = name;
if (typeof this.getName != "function") {
Person.prototype = {
constructor: Person,
getName: function () {
console.log(this.name);
}
}
}
}
var person1 = new Person('chris');
var person2 = new Person('daisy');
// 报错 并没有该方法
person1.getName();
// 注释掉上面的代码,这句是可以执行的。
person2.getName();
为了解释这个问题,假设开始执行var person1 = new Person('chris')
。
我们回想一下 new 的实现步骤:
- 首先新建一个对象
- 然后将对象的原型指向 Person.prototype
- 然后 Person.apply(obj)
- 返回这个对象
注意这个时候,回顾下 apply 的实现步骤,会执行 obj.Person 方法,这个时候就会执行 if 语句里的内容,注意构造函数的 prototype 属性指向了实例的原型,使用字面量方式直接覆盖 Person.prototype,并不会更改实例的原型的值,person1 依然是指向了以前的原型,而不是 Person.prototype。而之前的原型是没有 getName 方法的,所以就报错了!
如果你就是想用字面量方式写代码,可以尝试下这种:
function Person(name) {
this.name = name;
if (typeof this.getName != "function") {
Person.prototype = {
constructor: Person,
getName: function () {
console.log(this.name);
}
}
//将实例直接返回
return new Person(name);
}
}
var person1 = new Person('chris');
var person2 = new Person('daisy');
person1.getName(); // chris
person2.getName(); // daisy
5.1 寄生 - 构造函数模式
function Person(name) {
var o = new Object();
o.name = name;
o.getName = function () {
console.log(this.name);
};
return o;
}
var person1 = new Person('chris');
console.log(person1 instanceof Person) // false
console.log(person1 instanceof Object) // true
这个模式创建的实例使用 instanceof 都无法指向构造函数
这样方法可以在特殊情况下使用。比如我们想创建一个具有额外方法的特殊数组,但是又不想直接修改Array构造函数,我们可以这样写:
function SpecialArray() {
var values = new Array();
for (var i = 0, len = arguments.length; i < len; i++) {
values.push(arguments[i]);
}
values.toPipedString = function () {
return this.join("|");
};
return values;
}
var colors = new SpecialArray('red', 'blue', 'green');
var colors2 = SpecialArray('red2', 'blue2', 'green2');
console.log(colors);
console.log(colors.toPipedString()); // red|blue|green
console.log(colors2);
console.log(colors2.toPipedString()); // red2|blue2|green2
你会发现,其实所谓的寄生构造函数模式就是比工厂模式在创建对象的时候,多使用了一个new,实际上两者的结果是一样的。
但是作者可能是希望能像使用普通 Array 一样使用 SpecialArray,虽然把 SpecialArray 当成函数也一样能用,但是这并不是作者的本意,也变得不优雅。
在可以使用其他模式的情况下,不要使用这种模式。
但是值得一提的是,上面例子中的循环:
for (var i = 0, len = arguments.length; i < len; i++) {
values.push(arguments[i]);
}
完成可以替换成:
values.push.apply(values, arguments);
5.2 稳妥构造函数模式
function person(name){
var o = new Object();
o.sayName = function(){
console.log(name);
};
return o;
}
var person1 = person('chris');
person1.sayName(); // chris
person1.name = "daisy";
person1.sayName(); // chris
console.log(person1.name); // daisy
所谓稳妥对象,指的是没有公共属性,而且其方法也不引用 this 的对象。
与寄生构造函数模式有两点不同:
- 新创建的实例方法不引用 this
- 不使用 new 操作符调用构造函数
稳妥对象最适合在一些安全的环境中。
稳妥构造函数模式也跟工厂模式一样,无法识别对象所属类型。
补充
ES6创建对象
class person{
constructor(name){
this.name = name
}
sayName(){
console.log(this.name)
}
}
person.prototpye.hi = function(){console.log('2')}
new person('chris')
使用class定义类跟上面的构造函数+原型组合模式有一些相似之处,但又有所区别。
class定义的类上有个 constructor方法,这就是构造方法,该方法会返回一个实例对象,
this代表的就是实例对象,这跟上边的构造函数模式很类似。
es5与es6定义对象的区别:
-
class的构造函数必须使用new进行调用,普通构造函数不用new也可执行。
-
class不存在变量提升,es5中的function存在变量提升。
-
class内部定义的方法不可枚举,es5在prototype上定义的方法可以枚举。
我们可以用 Babel 转义一下:
'use strict'; // es6中class使用的是严格模式
// 处理class中的方法
var _createClass = 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);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
// 对构造函数进行判定
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
// class Person转换为 es5的function
var Person = function () {
function Person(age, name) {
// 调用了_classCallCheck检查Person是否为构造函数
_classCallCheck(this, Person);
this.name = name;
}
// 调用_createClass处理定义在class中的方法。
_createClass(Person, [{
key: 'sayName',
value: function sayName() {
console.log(this.name);
}
}]);
return Person;
}();
var person1 = new Person('chris');