正在对通过object.create创建的对象设置原型

Setting prototype on object created through Object.create

本文关键字:创建 对象 设置 原型 create object      更新时间:2024-05-15

在给定以下代码的情况下,我很难弄清楚原型链是如何设置的。

var Model = {
    prototype: {
        init: function(){},
        log: function(){ console.log('instance method log was called') }
    },
    log: function(){ console.log('class method log was called') },
    create: function() {
        var object = Object.create(this);
        object.parent = this;
        object.prototype = object.fn = Object.create(this.prototype);
        return object;
    },
    init: function() {
        var instance = Object.create(this.prototype);
        instance.parent = this;
        instance.init.apply(instance, arguments);
        return instance;
    }
}
var User = Model.create();
User.log(); // 'class method log was called'
// create a new method after creation
Model.warn = function() { console.warn('warn was called') }
User.warn() // 'warn was called'
var user = User.init();
user.log(); // 'instance method log was called'

具体来说,这句话在创建方法中让我感到困惑:

object.prototype = object.fn = Object.create(this.prototype);

我理解create方法是如何创建一个新对象的,该对象的原型指向Model,但倒数第二行似乎用新对象(Model.protype)覆盖了该原型。然而,原始原型似乎仍然完好无损,因为即使在创建了新对象后,我也可以向Model添加方法,并且新对象仍然可以访问它。

有人能告诉我们实际发生了什么吗?

编辑-我应该指出,此代码来自O'reilly

Javascript Web应用程序

好的。因此,对于删除噪声代码,您正在询问此代码:

var Model = {
    prototype: {},
    create: function() {
        var object = Object.create(this);
        object.prototype = Object.create(this.prototype);
        return object;
    }
};

create()函数的第一行很简单,它创建了一个扩展(原型)Model的新对象。

但是,由于下一行覆盖了对象"prototype"属性,因此您会感到困惑。它不是对象的原型,对象原型仍然是Model,它存储在一个名为[[prototype]]的隐藏属性上,代码正在修改的属性与对象的[[prototype]]无关,它只有相同的名称。让我们更改名称来理解它,它将是相同的:

var Model = {
    blablabla: {},
    create: function() {
        var object = Object.create(this);
        object.blablabla = Object.create(this.blablabla);
        return object;
    }
};

它扩展了Model.blablabla,因此当您更改object.blablabra时,它不会影响Model.blablabla.

var SubModel = Model.create();
SubModel.blablabla.newMethod = function() { };
console.log(Model.blablabla.newMethod); // undefined

很多时候,为字段选择正确的名称比它看起来更重要。