我正在学习 JS 中的 oop,我知道执行多个实例对象的“正确方法”是使用 var object = function(){}
但在学习时我做不同的事情来学习 JS 是如何工作的。
我将减少追逐,隐藏与这个问题无关的代码。
问题是,如果我使用以下代码,当我创建 Selectable 对象的两个实例时,我会在它们中获得相同的 id 属性。
var Selectable = {
create: function(type) {
Object.create(this);
this.type = type;
this.id = Math.random().toString(36).replace(/[^a-z]+/g, '').substring(0, 5);
return this;
}
};
但是,如果我这样做:
var Selectable = {
create: function(type) {
var _T = Object.create(this);
this.type = type;
this.id = Math.random().toString(36).replace(/[^a-z]+/g, '').substring(0, 5);
return Object.create(_T);
}
};
它们具有不同的 id 属性。 我确实阅读了有关 Object.create() 函数的内容,我了解到它使用所使用的模型对象的“原型(prototype)”创建一个新对象。但是为什么当我连续使用两个 Object.create() 函数创建对象时会起作用呢?
最佳答案
var Selectable = {
create: function(type) {
Object.create(this);
this.type = type;
this.id = Math.random().toString(36).replace([^a-z]+/g, '').substring(0, 5);
return this;
}
};
alert(selectable.create());
你的函数最终返回了这个。但这不是创建的对象,它仍然是可选择的。此外,您还可以在设置对象的 id 和类型之前克隆该对象。做:
var selectable={
create:function(type){
obj=Object.create(this);
obj.type=type;
obj.id=whatever;
return obj;
};
}
关于javascript - 在文字对象上使用 Object.create 的奇怪行为和多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39277503/