根据这篇 MSDN 文章- 滚动到Constructor Functions but No Classes
,(并且在阅读了MDN JS参考之后)我应该能够构造一个像这样的对象:
function Dog(name){
this.name = name;
}
// EXAMPLE 1
var dog = new Dog("Spot");
console.log("Dog using new:");
console.log(dog); // Dog object, awesome!
// EXAMPLE 2
var dog = {};
dog = Dog.call(dog,"Rowdie");
console.log("Dog using call:");
console.log(dog); // Undefined.. why?
但是,虽然第一个示例(构造新对象的最常见方式)返回了预期的实例,但第二个示例返回了undefined
- 我做错了什么吗?
这是我用来测试这个的 JSFiddle:http: //jsfiddle.net/wk8JD/1/