对象的新实例充当参考? [英] new instance of object acting as reference?
问题描述
我在创建对象的新实例时遇到问题.
I am having a problem creating new instances of an object.
使用下面的代码,我希望每个元素都有它自己的随机值(正在发生).
Using the below code I was expecting each element to have it's own random value (which is happening).
但是后来我还希望对象的每个实例都包含this.element
值,但是每次在对象的任何实例中更改值时,它都会在所有对象中都更新.
But then I was also expecting the this.element
value to be contained to each instance of the object, but instead every time the value is changed in any instance of the object it is updating in all of them.
var Instance = function(element) {
this.$element = $(element);
this.subInstance.parent = this;
}
Instance.prototype = {
subInstance: {
parent: null,
$element: null,
init: function() {
var $this = this;
this.$element = this.parent.$element;
//test for what this.$element refers to in init function
var random = Math.random();
$('.element', this.$element).text('Updated ' + random);
//test for what this.$element refers to in an event handler
$('.element', this.$element).on('click', function(e) {
$this.$element.css('background-color', '#f00');
});
}
}
}
$('div.instance').each(function(i, o) {
var instance = new Instance(o);
instance.subInstance.init();
});
现在我知道我可以使用this.subInstance = {...
将子实例移出原型并移入构造函数中,但这似乎是错误的,为什么对象的每个实例中都不包含this.$element
?
Now I know I could move subInstance out of the prototype and into the constructor using this.subInstance = {...
but that seems wrong, why is this.$element
not contained to each instance of the object?
两个示例的JSFiddle: http://jsfiddle.net/q7zAg/
JSFiddle of both examples: http://jsfiddle.net/q7zAg/
推荐答案
这似乎是错误的,但事实并非如此.如果从构造函数创建的每个对象都需要使用唯一的subInstance
,则需要为每个单独的实例创建一个新对象.在prototype
上,它将被共享.
It may seem wrong, but it's not. If each object created from the constructor needs to work with a unique subInstance
, you'll need to create a new one for each individual instance. On the prototype
it will be shared.
但是,您可以做的一件事是使用Object.create
创建一个继承自原型subInstance
的新实例.然后,您将获得一些重用的好处,并且每个实例都可以修改自己的对象.
However, one thing you could do would be to use Object.create
to create a new instance that inherits from the prototyped subInstance
. Then you get the benefit of some reuse, and each instance can modify its own object.
var Instance = function(element) {
this.$element = $(element);
this.subInstance = Object.create(this.subInstance);
this.subInstance.parent = this;
}
现在,有些人可能会争辩说,subInstance
仍然不应该在prototype
上,而应该是IIFE中的局部变量.我倾向于同意这一点.
Now some may argue that the subInstance
still shouldn't be on the prototype
, but rather should be a local variable in an IIFE. I would tend to agree with this.
这是一个例子:
var Instance = (function() {
var _subInstance = {
parent: null,
$element: null,
init: function() {
// ...
}
};
var Instance = function(element) {
this.$element = $(element);
this.subInstance = Object.create(_subInstance);
this.subInstance.parent = this;
};
// other prototyped props
Instance.prototype.foo = "bar";
return Instance;
})();
这篇关于对象的新实例充当参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!