2012-03-01 48 views
2
var Person = function(name, age){ 
    return Object.create(Object.prototype, { 
     name: { 
      value: name | "", 
      writable: true, 
      enumerable: true, 
      configurable: true 
     }, 
     age: { 
      value: age | "", 
      writable: true, 
      enumerable: true, 
      configurable: true 
     } 
    }); 
}; 

var Boy = function(name, age){ 
    return Object.create(Person(name, age), { 
     gender: { 
      value: "male" 
     } 
    }); 
}; 

var p = Person("John", 28); 
var b = Boy(); 

console.log(p.isPrototypeOf(b)); // false? 

我想了解object.create以及如何最好地使用它避免使用构造函数new关键字。到目前为止,我正在接近它(虽然可能不是最好的方法,只是试验和错误) - 并发现如果我使用object.create我不再能够检查instanceof和对象类型。Javascript object.create和isPrototypeOf

有人建议使用isPrototypeOf检查 - 我做错了,因为我上面的代码在检查时返回false

是否有人会友善地解释我哪里出错了?我仍然对JavaScript中的原型继承不熟悉。

回答

2

当然p不是b的原型。

这是因为Person函数每次都返回一个新的Object。

请尝试以下

var Boy = function(person, name, age){ 
    return Object.create(person, { 
     gender: { 
      value: "male" 
     } 
    }); 
}; 


var p = Person("John", 28); 
var b = Boy(p); 
assert(p.isPrototypeOf(b))