在我的主模板文件中,我有这个
var Product = function(){
this.is_active = true,
this.is_bom_enabled = false;
};
现在我需要修改Product
,主要是我需要添加更多属性。
我试过
Product.someOtherThing = value; // only work for `Product` and not for new instances
毕竟
var SONY = new Product();
SONY.is_active; // true;
SONY.someOtherThing; //undefined
如何更改Product
以后的属性?
答案 0 :(得分:2)
Product
被用作构造函数。当您使用函数作为构造函数(通过new
运算符)时,它会执行以下操作:
new
创建一个新的空白对象,并将FunctionName.prototype
指定为对象的原型。
new
调用您的构造函数,this
引用该新对象。
(在正常情况下。)new
表达式的结果是对该新对象的引用。
因此,您的代码在Product
函数中执行的操作是将属性分配给通过new
创建的对象。如果要添加到该对象,只需添加到该对象:
var p = new Product();
p.someOtherThing = "some value";
如果要在原型上创建属性,请将它们分配给Product.prototype
对象。
Product.prototype.someCommonProperty = "some value";
当您引用对象上的属性时,JavaScript引擎首先查看对象本身以查看它是否具有该属性。如果没有,引擎会查看对象的 prototype 以查看它是否具有该属性(然后是原型的原型等)。因此,向原型添加属性使它们可以通过使用该原型的实例获得。
让我们看一下你的Product
:
var Product = function(){
this.is_active = true,
this.is_bom_enabled = false;
};
var p = new Product();
p
引用的对象包含拥有属性is_active
和is_bom_enabled
。它们不是来自它的原型。如果我们这样做:
Product.prototype.someCommonProperty = "some value";
...然后,如果你执行p.someCommonProperty
,引擎首先会查看p
是否有自己的属性someCommonProperty
,并且由于它没有,引擎会查看原型。由于原型有它,它从那里获得价值。
请注意,使用原型中的属性是不对称的:从对象获取属性值将使用原型的版本,但设置属性值将始终将其设置为实际的对象。所以:
console.log(p.someCommonProperty); // "some value" -- from the prototype
p.someCommonProperty = "foo"; // Adds the property to `p`, doesn't change the prototype
console.log(p.someCommonProperty); // "foo" -- from `p`, not the prototype
答案 1 :(得分:1)
var Product = function(){
this.is_active = true,
this.is_bom_enabled = false;
};
Product.prototype.someOtherThing = value;
var SONY = new Product();
SONY.is_active; // true;
SONY.someOtherThing; //value