为什么此语法会导致它的 属性 构造函数不再指向它自己的构造函数?
Why does this syntax cause it's property constructor to longer point to it's own constructor?
我正在学习 JavaScript 中的原型,遇到了这种行为,我想这只是一个事实,但想知道是否有任何实际原因...
假设您创建了一个对象:
function Stormtrooper(){}
然后想用一些属性和方法快速填充它,因为毕竟它们是 Stormtroopers,它们将是相同的 :)(还有一个更好的理由,您不希望创建的每个实例都具有它拥有单独的属性和方法,这会浪费内存并导致重复)。
Stormtrooper.prototype = {
name : null,
type: null,
ID : null,
rank : null,
'years of service' : null,
weapon : null,
utilityBelt : null,
giveReport : function(){
alert('"Click.." This is '+ this.type +' ' + this.ID + ', everything is clear... Nothing to report..."Click"');
}
};
当你 console.dir(Stormtrooper.prototype);
打开 __proto__:
属性 然后查看它的 constructor
属性,它会指向 Object
, as in the be all end all native Object.为什么?
我知道您可以在最初创建时明确添加 constructor
属性,但想知道这是为什么? (它指向 Object
而不是 Stormtrooper
)。
提前致谢!
从对象文字创建的任何对象:
var obj = { hello: "world" };
将是一个由 Object 构造函数构造的普通对象。这正是您在代码中得到的:
Stormtrooper.prototype = {
// ...
};
我正在学习 JavaScript 中的原型,遇到了这种行为,我想这只是一个事实,但想知道是否有任何实际原因...
假设您创建了一个对象:
function Stormtrooper(){}
然后想用一些属性和方法快速填充它,因为毕竟它们是 Stormtroopers,它们将是相同的 :)(还有一个更好的理由,您不希望创建的每个实例都具有它拥有单独的属性和方法,这会浪费内存并导致重复)。
Stormtrooper.prototype = {
name : null,
type: null,
ID : null,
rank : null,
'years of service' : null,
weapon : null,
utilityBelt : null,
giveReport : function(){
alert('"Click.." This is '+ this.type +' ' + this.ID + ', everything is clear... Nothing to report..."Click"');
}
};
当你 console.dir(Stormtrooper.prototype);
打开 __proto__:
属性 然后查看它的 constructor
属性,它会指向 Object
, as in the be all end all native Object.为什么?
我知道您可以在最初创建时明确添加 constructor
属性,但想知道这是为什么? (它指向 Object
而不是 Stormtrooper
)。
提前致谢!
从对象文字创建的任何对象:
var obj = { hello: "world" };
将是一个由 Object 构造函数构造的普通对象。这正是您在代码中得到的:
Stormtrooper.prototype = {
// ...
};