Ole*_*lex 1 javascript oop prototype
Person.prototype和之间有什么区别Object.create(Person.prototype)?我可以使用它们吗?
function Person(name) {
this.name = name;
}
Person.prototype.copy = function() {
return new this.constructor(this.name);
};
// define the Student class
function Student(name) {
Person.call(this, name);
}
// inherit Person
Student.prototype = Person.prototype;
//Student.prototype = Object.create(Person.prototype);
Run Code Online (Sandbox Code Playgroud)
最好用 Student.prototype = Object.create(Person.prototype) 而不是Student.prototype = Person.prototype;
原因是在后一种情况下两个原型共享一个共同的对象.因此,我们在Student原型中添加一个新方法,人物原型也将被访问该属性.例如:-
Student.prototype = Person.prototype
Student.prototype.test = function(){ alert('in student');};
var person = new Person();
person.test();
Run Code Online (Sandbox Code Playgroud)
这将提醒'在学生'
| 归档时间: |
|
| 查看次数: |
459 次 |
| 最近记录: |