gpt4 book ai didi

JavaScript:构建新实例的方法

转载 作者:行者123 更新时间:2023-11-30 07:41:01 24 4
gpt4 key购买 nike

根据 this MSDN article - 滚动到 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/

最佳答案

改变

dog = Dog.call(dog,"Rowdie");

Dog.call(dog,"Rowdie");

当您使用 new 调用函数时,this 将被隐式 返回,即该函数的行为就好像您有 return this; 最后。来自MDN documentation :

The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

但是如果你“正常”调用一个函数(即没有 new),如果没有 return 语句,它将返回 undefined

(顺便说一句,在文章中他们也没有分配返回值)

关于JavaScript:构建新实例的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17164522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com