Introduction to Object-Oriented JavaScript一度让我感到困惑。
他们定义了一个 Person
类,如下所示:
Properties should be set in the prototype property of the class (function) so that inheritance works correctly.
function Person(gender) {
this.gender = gender;
alert('Person instantiated');
}
Person.prototype.gender = '';
稍后当他们给出继承示例时,他们删除了 gender
属性(为了清楚起见,我假设),所以我不确定 Person.prototype.gender = '' 这行是什么;
放在首位。
我试过这个:
function Person(gender) {
this.gender = gender;
}
Person.prototype.gender = 'default';
function Student(gender) {
Person.call(this, gender);
};
Student.prototype = new Person();
Student.prototype.constructor = Student;
var a = new Student('male');
var b = new Student();
console.log(a.gender); //prints 'male'
console.log(b.gender); //I expect 'default', but get undefined
最佳答案
如果你想从原型(prototype)继承它的值,你不能直接在对象上设置属性。
function Person(gender) {
if (typeof gender !== 'undefined') this.gender = gender;
}
此外,当唯一目标是设置原型(prototype)链时,请避免更新对象。在某些情况下,像下面这样使用 new
可能会产生不良副作用。
Student.prototype = new Person();
应替换为:
Student.prototype = Object.create(Person.prototype);
关于Javascript 原型(prototype)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23727550/