gpt4 book ai didi

javascript - 对象的构造函数属性被省略

转载 作者:行者123 更新时间:2023-12-03 12:14:06 26 4
gpt4 key购买 nike

我定义了一个简单的 JavaScript 类

function Demo(a,b){
this.a=a;
this.b=b;
}

//and Demo objects inherit from the prototype
Demo.prototype = {
toString : function() { return this.a + " " + this.b ; }
}

//usage
var d = new Demo("Hello","world");
console.log(d);

但是实例没有构造函数属性。这是为什么?我的意思是当我这样做时

console.log(d.constructor) //function Object() { [native code] } 

最佳答案

对象文字(大括号)继承自 Object,因此构造函数属性将与 Object 的属性相同,除非您使用自己的值覆盖它,就像 zzzzBov 的答案中那样。如果像 Demo.prototype = new Object(); 那样直接从 Object 继承,将会得到相同的结果。

从继承自 Function 的对象继承可以为您提供所需的构造函数属性,而无需您自己定义它。试试这个:

function DemoBase(a,b){
this.toString=function() { return this.a + " " + this.b ; }
}

function Demo(a,b){
this.a=a;
this.b=b;
}
Demo.prototype = new DemoBase();

//usage
var d = new Demo("Hello","world");
console.log(d);
console.log(d.constructor)

关于javascript - 对象的构造函数属性被省略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24811079/

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