javascript 的原型繼承, Object.create(), 和new之間的關係
阿新 • • 發佈:2019-02-08
原型繼承是道格拉斯-克羅克福德提出來的, Object.create() 是ES5新增的, new是建構函式的標準用法。
原型式繼承的建構函式為
function object(o) {
function F(){}
F.prototype = o;
return new F();
}
我先用《javascript高階程式設計》裡的例子
//這是在瀏覽器裡執行的結果 var person = { name: 'john', friends : ["a", "b", "c"] }; undefined var a1 = Object.create(person); undefined function object(o) { function F(){} F.prototype = o; return new F(); } undefined var a2 = object(person); undefined a1.__proto__ === person; true a2.__proto__ === person; true
通過上面的執行結果,我們可以看到object和object.create()的執行結果一樣。相當於他們都繼承了F.prototype這個隊象的方法和屬性。
function Person(name) { this.name = name; } undefined var b1 = new Person('ly'); undefined var b2 = Object.create(Person, { name: { value: 'ly' } }); undefined b1.__proto__ === Person.prototype true b2.__proto__ === Person true
由上面的執行結果,可以看出由Object.create()函式生成的例項始終指向建構函式,而不是建構函式的原型。
b2.__proto__ === F.prototype = Person, 並且F.prototype被重新賦值,所以其constructor屬性是沒有的。