JS原型设计模式(四)之缺陷(一)

前面三篇介绍的都是原型设计模式的好处,今天说说原型模式的弊端:1.构造函数指向需要手工写入2.对于引用类型来说有共享问题的错误

var Person = function () {
    this.class='ddd';
    this.toString=function(){};
};
Person.prototype.name = 'tlc';
Person.prototype.age = '25';
Person.prototype.sex = 'boy';
Person.prototype.sayInfo = function () {
    console.info(this.name + "--" + this.age + "--" + this.sex)
};
每次为原型对象添加属性或者方法的时候都要重新写一遍Person.prototype这个字段,这样的写法太过复杂,所以可以将Person.prototype给指向一个对象,而这个对象中包含所需要的属性和方法

var Person = function () {
};
Person.prototype = {
    name: 'tlc',
    age: '19',
    sex: 'boy',
    sayInfo: function () {
        console.info(this.name + "--" + this.age + "--" + this.sex)
    }
};
所以出现了原型对象的constructor指向不是Person的问题,因为上述代码相当于重写原型对象,而在js中每此创建创建函数的时候都会创建一个原型对象,所以上述代码之后的constructor指向新创建的对象constructor

var person1 = new Person();
console.log(person1.constructor == Person);//false
console.info(person1.constructor == Object);//true
可以手动添加constructor属性,但是这个属性是可以枚举的,如果不想这个属性可以枚举,可以使用defineProperty方法之后就不能枚举此属性

Person.prototype = {
    constructor:Person,
    name: 'tlc',
    age: '19',
    sex: 'boy',
    sayInfo: function () {
        console.info(this.name + "--" + this.age + "--" + this.sex)
    }
};
var person1 = new Person();
console.log(person1.constructor == Person);//true
console.info(person1.constructor == Object);//false
Object.defineProperty(Person.prototype,'constructor',{
    enumerable:false,
    value:Person
});


你可能感兴趣的:(js随笔)