parent is the parent class, child inherits parent, when the value of sex of the child instance is modified When parent and other subclass instancessex will be changed; In the constructor
, or it is agreed that the object attribute in the prototype is not allowed to be modified to avoid the impact of subclass instances on the parent class and other subclasses; Are there any other solutions? plan?
function extend(p, c) {
var f = function () {};
f.prototype = p.prototype;
c.prototype = new f();
c.prototype.constructor = c;
}
function parent() {}
parent.prototype.aaa = 123;
parent.prototype.sex = ['男', '女'];
function child() {}
extend(parent, child);
c1 = new child();
c2 = new child();
console.log('设置实例c1之前,父类的sex值:',parent.prototype.sex);
console.log('设置实例c1之前,实例c2的sex值:',c2.sex);
c1.sex.push('其他');
console.log('设置实例c1之后,父类的sex值:',parent.prototype.sex);
console.log('设置实例c1之后,实例c2的sex值:',c2.sex);
This method allows subclasses and objects to access sex. If sex does not exist, a copy of the parent class sex will be created for it. If it exists, it will be returned directly.
The subclass defines an attribute with the same name, overriding the parent class’s?
Non-method attributes are not recommended to be set on the prototype
When initializing the subclass
child
, define private properties: