本文介绍了Javascript原型和实例创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉,因为这个话题出现了很多,但是我今天读到的任何东西都没能充分解释。

I apologize because this topic comes up a lot, but I have not been able to have this adequately explained in anything I've read today.

我正在尝试创建一个简单的集合类(并同时学习javascript原型),用于存储具有name属性的对象,并允许其成员通过索引或值访问。到目前为止,我已经得到了这个:

I am trying to make a simple collection class (and learn about javascript prototyping at the same time) designed to store objects with a "name" property and lets its members be accessed by index or value. So far I've got this:

function Collection() {}
Collection.prototype.constructor = Collection;
Collection.prototype._innerList = [];
Collection.prototype._xref = {};
Collection.prototype.count = function () { return this._innerList.length; };
Collection.prototype.add = function (obj) {
    this._xref[obj.name] = this._innerList.push(obj) - 1;
}
Collection.prototype.get = function (id) {
    if (typeof id == "string") {
        return this._innerList[this._xref[id]];
    } else {
        return this._innerList[id];
    }
};

问题:

var foo = new Collection();
foo.add({name: "someitem", value:"hello world"});   // foo.count()== 1

var bar= new Collection();
bar.add({name: "someotheritem", value:"hello world"}); // bar.count()== 2

嗯......

基本上,创建新实例 bar ,其中所有属性都具有 foo中数据的当前值。我知道我可以通过在构造函数中放置_xref等来解决这个问题,但我正在尝试理解原型如何工作。如果我创建一个新实例,并对该实例中的数据进行更改,那么当我创建另一个新实例时,为什么这些值会继续?

Basically, the new instance bar is created with all the properties having the current values of the data in foo. I know I can fix this by putting _xref, etc. inside the constructor, but I'm trying to understand how prototyping works. If I create a new instance, and make changes to the data in that instance, why would those values carry over when I create another new instance?

如果我从 foo bar的原型进一步更改属性它们是独立的,所以看起来好像我在某种程度上引用了同一个实例。那么是什么导致 bar 用来自 foo 的当前值进行实例化?

If I make further changes to a property from the prototype of foo or bar they are independent, so it doesn't seem as if I'm somehow referencing the same instance of anything. So what is causing bar to be instantiated with the current values from foo?

推荐答案

考虑一个满是学生的教室。把东西放在原型上就像把东西放在白板上让所有人看到。当你宣布

Consider a classroom full of students. Putting something on the prototype is like putting something on the white board for them all to see. When you're declaring

Collection.prototype._innerList = [];

你给每个收藏品一个属性;无论是调用新的Collection(),白板的任何更改都会影响所有学生。但是,如果您在构造函数中定义它,或者在 this.variableName = [] 中定义其中一个函数,则每个副本都将拥有自己的variableName,就像给每个学生分发一份讲义一样。显然,在某些情况下,可以在白板上放置一些东西,例如从学生到学生的通用说明,但如果每个学生的每个项目都不同,那么它应该是个人财产。希望这个解释有意义......

you're giving every collection that property; regardless of calling new Collection() any changes to the white board affects all students. However, if you define it within the constructor, or one of the functions as this.variableName = [], each copy will have its own variableName, like handing each student a handout. Obviously, there's some cases when it's okay to have something on the white board, such as instructions that will be universal from student to student, but if each item is going to be different for each student, it should be an individual property. Hope this explanation makes sense...

你想这样做。

function Collection() {
    if (!this instanceof Collection)
        return new Collection();
    this._innerList = [];
    this._xref = {};

    return this;
}

Collection.prototype.count = function() {
    return this._innerList.length;
};
Collection.prototype.add = function(obj) {
    this._xref[obj.name] = this._innerList.push(obj) - 1;
}
Collection.prototype.get = function(id) {
    if (typeof id == "string") {
        return this._innerList[this._xref[id]];
    } else {
        return this._innerList[id];
    }
};

var foo = new Collection();
foo.add({name: "someitem", value:"hello world"});
console.log(foo.count()); // 1

var bar= new Collection();
bar.add({name: "someotheritem", value:"hello world"});
console.log(bar.count()); // 1

不与你的问题真的相关,但这是我做的事情,所以我会把它扔出去。每当我在原型上做某事时,如果我没有返回某些东西,我会返回这个。它允许链接,所以你可以做 instance.function1()。function2()。function3()只要 function1 function2 返回

Not really relevant to your question, but it's something I do so I will throw it out there. Whenever I'm doing something on the prototype, if I'm not returning something, I return this. It allows chaining, so you could do instance.function1().function2().function3() as long as function1 and function2 return this.

这篇关于Javascript原型和实例创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 19:04