2015-06-08 53 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