情况:
我有多个具有相同结构的JS对象。
在所有这些对象中,都有一个称为console的属性。
我想为每个属性分配一个值(相同的值)。
请在我的代码的结构下面找到:
NameOfMyObject = function() {
return {
actions: null,
console: null,
init: function() {},
//object specific functions
}
};
我的问题:
目前,我正在分配价值手册,但我想这样做是通用的。
代码段
this.console = console;
this.actions.console = console;
this.fixtures.console = console;
如何访问对象的属性?
我希望我的问题足够清楚。
答案 0 :(得分:1)
这里是如何在对象之间共享属性:
function MyClass() {};
MyClass.prototype.console = {}; // Define a "common" property on the prototype
var obj1 = new MyClass(); // Create two instances
var obj2 = new MyClass();
Object.getPrototypeOf(obj1).console.id = 13; // Assign a value once...
console.log(obj1.console.id); // ... and it exists on both instances
console.log(obj2.console.id);
共享属性位于原型对象上。
您当然可以使用Object.getPrototypeOf(obj1)
来代替MyClass.prototype
,因为您知道obj1
由MyClass
创建。它们给出相同的原型对象。
如果您的属性始终有一个对象作为值,并且您不需要替换该值,只需通过在该对象上设置属性来对其进行变异,则无需显式引用设置新值的原型。
这可行:
function MyClass() {};
MyClass.prototype.console = {}; // Define a "common" property on the prototype
var obj1 = new MyClass(); // Create two instances
var obj2 = new MyClass();
obj1.console.id = 13; // Assign a value once... (getting console from the prototype)
console.log(obj1.console.id); // ... and it exists on both instances
console.log(obj2.console.id);
但是,如果您自己更改console
,则将在实例上而不是在原型上进行设置:
function MyClass() {};
MyClass.prototype.console = {}; // Define a "common" property on the prototype
var obj1 = new MyClass(); // Create two instances
var obj2 = new MyClass();
obj1.console = { id: 13}; // Setting an instance property now
console.log(obj1.console.id); // ... and it does not exist on both instances
console.log(obj2.console.id); // == undefined
因此,如果这种分配仍然可以在原型上运行,则需要将第一个代码块与Object.getPrototypeOf
或MyClass.prototype
一起使用。