奇怪的行为和使用Object的多个实例.在文字对象上创建

Strange behavior and multiple instances using Object.create on literal objects

本文关键字:实例 文字 对象 创建 Object      更新时间:2023-09-26

我正在学习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()函数,我学到的是它使用模型对象的"原型"创建一个新对象。但是,当我在一行中使用两个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;
};
}