2015-06-08 50 views
1

在這裏工作是我的代碼:的Object.create不是在功能

function Mammal(name){ 
    this.name = name; 
    this.offspring = []; 
} 

Mammal.prototype.sayHello = function(){ 
    return "My name is " + this.name + ", I'm a " + this.constructor.name; 
} 



function Cat(name, color){ 
    Mammal.call(this, name); 
    this.color = color; 
} 

現在,當我打電話的Object.create從這個函數:

function extendWithObjectCreate(child, parent) { 
    child.prototype = Object.create(parent.prototype);  
    child.prototype.constructor = child; 
} 

的Object.create不返回一個對象鏈接到父級原型。

你可以在函數中使用Object.create嗎?

+2

你能解釋你如何調用'extendWithObjectCreate'嗎? –

+0

如何將'child'和'parent'傳遞給'extendWithObjectCreate'? –

+0

extendWithObjectCreate(Child,Mammal) – HelloWorld

回答

0

當我做到這一點,它出來就好了:

function Mammal(name) { 
 
    this.name = name; 
 
    this.offspring = []; 
 
} 
 

 
Mammal.prototype.sayHello = function() { 
 
    return "My name is " + this.name + ", I'm a " + this.constructor.name; 
 
} 
 

 
function Cat(name, color) { 
 
    Mammal.call(this, name); 
 
    this.color = color; 
 
} 
 

 
function extendWithObjectCreate(child, parent) { 
 
    child.prototype = Object.create(parent.prototype);  
 
    child.prototype.constructor = child; 
 
} 
 

 
extendWithObjectCreate(Cat, Mammal); 
 

 
alert(new Cat('Muffin','blue').sayHello());

原型工作。但是,因爲Object.create()使用原型創建了一個對象,所以原型屬性未在對象本身上設置。所以,雖然Cat.prototype.sayHello存在,但Cat.prototype.hasOwnProperty('sayHello')是錯誤的。

+0

@Qantas Chrome也有'Object.hasOwnProperty'。 – Scimonster

+0

啊,我錯了,Firefox沒有。這並不符合你的想法,因爲它會在「對象」而不是「Cat.prototype」上調用它。 –

+0

啊。那麼我的錯誤。感謝您修復它。 – Scimonster