2015-07-19 93 views
2

Person.prototypeObject.create(Person.prototype)有什麼區別?我可以使用他們每個人嗎?Javascript Object prototype and Object.create method

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); 
+0

http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/ – SLaks

+2

參見:[使用「Object.create」而不是「新」](http://stackoverflow.com/q/2709612/4639281) –

回答

7

這是更好地使用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(); 

這將 '學生' 提醒

+0

給我你的代碼和** Student.prototype = Object.create(Person.prototype)**也警報'在學生'。所以他們分享相同的參考。那麼,有什麼不同呢? –

+1

你可以試試這個,如果你得到警報 功能學生(){} 功能的人(){} Student.prototype =的Object.create(Person.prototype的); Student.prototype.test = function(){alert('in student');}; var person = new Person(); person.test(); – abs

+1

@Olegalex:這是不可能的,你不能只用Object.create得到相同的結果。 –

相關問題