为什么 Object.create 在 JavaScript 中的原型继承方面没有做我所期望的

Why Object.create is not doing what I expect in terms of prototypal inheritance in JavaScript

本文关键字:方面没 期望 继承 原型 create Object JavaScript 为什么      更新时间:2023-09-26

我仍在努力掌握这个 JS 继承的东西是如何工作的,每次我认为我都有它......我显然没有。

尝试 1

链接: https://jsfiddle.net/jacquesvanderhoven/4qkvdn46/

法典

var baseSettings = function ()
{
    this.message = "base message";
    this.getMessage = function(){
        return  "base message from function";
    }
};
var homeSettings = function ()
{
    this.name = "name";
    this.getName = function()
    {
        return "name from function";
    };
};
homeSettings.prototype = Object.create(baseSettings);
var $log = $("#log");
var base = new baseSettings();
var home = new homeSettings();
$log.html($log.html() + "<br /> baseSettings.message: '" + base.message + "'");
$log.html($log.html() + "<br /> baseSettings.getMessage(): '" + base.getMessage() + "'");
$log.html($log.html() + "<br /> homeSettings.name: '" + home.name + "'");
$log.html($log.html() + "<br /> homeSettings.getName(): '" + home.getName() + "'");
$log.html($log.html() + "<br /> homeSettings.message: '" + home.message + "'");
$log.html($log.html() + "<br /> homeSettings.getMessage(): '" + home.getMessage() + "'");

结果

baseSettings.message: 'base message'
baseSettings.getMessage(): 'base message from function'
homeSettings.name:"
homeSettings.getName(): 'name from function'
主页设置消息:"未定义"

其中两个实际上会抛出 JS 异常。


诱惑 2

如果我向超级构造函数添加调用,它会稍微改变一些事情:
链接: https://jsfiddle.net/jacquesvanderhoven/4qkvdn46/5/

法典

var baseSettings = function ()
{
    this.message = "base message";
    this.getMessage = function(){
        return  "base message from function";
    }
};
var homeSettings = function ()
{
    baseSettings.call(this);
    this.name = "name";
    this.getName = function()
    {
        return "name from function";
    };
};
homeSettings.prototype = Object.create(baseSettings);
var $log = $("#log");
var base = new baseSettings();
var home = new homeSettings();
$log.html($log.html() + "<br /> baseSettings.message: '" + base.message + "'");
$log.html($log.html() + "<br /> baseSettings.getMessage(): '" + base.getMessage() + "'");
$log.html($log.html() + "<br /> homeSettings.name: '" + home.name + "'");
$log.html($log.html() + "<br /> homeSettings.getName(): '" + home.getName() + "'");
$log.html($log.html() + "<br /> homeSettings.message: '" + home.message + "'");
$log.html($log.html() + "<br /> homeSettings.getMessage(): '" + home.getMessage() + "'");

结果

baseSettings.message: 'base message'
baseSettings.getMessage(): 'base message from function'
homeSettings.name:"(注意!这是空的,不应该是)
homeSettings.getName(): 'name from function'
主页设置消息:"基本消息"
homeSettings.getMessage(): '来自函数的基本消息'

它们中的大多数都有效,但我无法弄清楚为什么 homeSettings.name 什么也没返回?

在我看来,Object.create 实际上什么都不做,或者更确切地说,它需要调用超构造函数才能产生任何影响,但即便如此,它也不是完美的。


尝试 3

删除对 Object.create 的调用,并将调用留给超级构造函数。
链接: https://jsfiddle.net/jacquesvanderhoven/4qkvdn46/8/

法典

var baseSettings = function ()
{
    this.message = "base message";
    this.getMessage = function(){
        return  "base message from function";
    }
};
var homeSettings = function ()
{
    baseSettings.call(this);
    this.name = "name";
    this.getName = function()
    {
        return "name from function";
    };
};
var $log = $("#log");
var base = new baseSettings();
var home = new homeSettings();
$log.html($log.html() + "<br /> baseSettings.message: '" + base.message + "'");
$log.html($log.html() + "<br /> baseSettings.getMessage(): '" + base.getMessage() + "'");
$log.html($log.html() + "<br /> homeSettings.name: '" + home.name + "'");
$log.html($log.html() + "<br /> homeSettings.getName(): '" + home.getName() + "'");
$log.html($log.html() + "<br /> homeSettings.message: '" + home.message + "'");
$log.html($log.html() + "<br /> homeSettings.getMessage(): '" + home.getMessage() + "'");

结果

baseSettings.message: 'base message'
baseSettings.getMessage(): 'base message from function'
homeSettings.name:"名称"
homeSettings.getName(): 'name from function'
主页设置消息:"基本消息"
homeSettings.getMessage(): '来自函数的基本消息'

结论

正在研究我在 SO 上看到的各种示例,我不得不承认我还没有达到理解为什么继承在 JS 中有效或不起作用的地步。我遇到的另一个问题是,在各种测试中,"this"的上下文发生了变化,我知道这种情况会发生,但我似乎无法很好地理解为什么或何时,以便我确切地知道发生了什么。

JavaScript 中继承的关键是原型链。每当发生属性查找时:

something.propertyName

运行时首先检查直接引用的对象。如果未找到该属性,则搜索由原型内部属性链接的对象链(通常只是一个对象)的过程。

因此,使继承工作的关键是创建具有原型链的对象。这样做的传统方法是使用 new 运算符和构造函数:

function Constructor() {}
Constructor.prototype = {
  propertyName: function() { alert("hello world"); }
};

现在可以创建一个对象:

var something = new Constructor();

和引用的属性:

something.propertyName(); // "hello world"

请注意,此构造函数不会执行任何操作。 它可以做一些事情,但它通过存在并拥有该原型对象来实现其在使继承工作方面的作用。

Object.create()函数只是使用原型链制作对象的另一种方式:

var something = Object.create({
  propertyName: function() { alert("hello world"); }
});
something.propertyName(); // "hello world"

那也可以写

var something = Object.create(Constructor.prototype);

以重用第一个示例中的原型对象。

当然,当用作原型的对象是在代码中创建并为此目的保留的某个对象时,Object.create()更有意义,而不是像我上面的例子那样的动态对象。要使用测试代码,请执行以下操作:

var baseSettings = { // plain object, not a constructor
  message: "base message",
  getMessage: function() {
    return "base message: " + this.message;
  }
};
var homeSettings = Object.create(baseSettings, {
  name: "home name",
  getName: function() {
    return "home name: " + this.name;
  }
});

现在可以使用homeSettings作为原型创建对象,它们将从该对象继承namegetName,并从baseSettings对象继承messagegetMessage

var x = Object.create(homeSettings);
console.log(x.name); // "home name"
console.log(x.getName()); // "home name: home name"
console.log(x.message); // "base message"
console.log(x.getMessage()); // "base message: base message"

这本可以用构造函数而不是Object.create()来完成:

function HomeBase() {};
HomeBase.prototype = homeSettings;
var x = new HomeBase();

相同的console.log()调用序列将产生相同的结果。无论哪种情况(通过new还是通过Object.create()),x在这些示例中引用的对象都没有自己的属性。

代码中的主要问题是这一行:

homeSettings.prototype = Object.create(baseSettings);

你正在将函数构造函数传递给 Object.create 当它只需要一个对象时。在这种情况下,它只会返回一个空对象。

使用 Object.create 进行继承非常简单。

//Base class
function Vehicle() {
  this.name = "vehicle " + parseInt( Math.random()*100 );
}
Vehicle.prototype.getName = function () {
  console.log( this.name );
};
//sub class
function Bike() {}
Bike.prototype = Object.create( Vehicle.prototype );
var honda = new Bike();

但是,请注意,仅设置了原型引用,构造函数 Vehicle 永远不会执行。因此,不会复制基类中定义的公共属性。因此,Bike 类将具有启动方法,但没有名称属性。

通过调用

具有上下文作为子类的基类调用方法,可以在一定程度上解决此问题,如下所示。

通过在子类中调用 Base 类调用方法,我们可以将属性从 Base 复制到 Sub 类。

但是,属性是按实例复制的,而不是在原型上复制的,因此这需要更多的内存。

function Scooter() {
  //runs on creating every new instance so the name property is copied to each instance not to prototype
  Vehicle.call(this);
}
Scooter.prototype = Object.create( Vehicle.prototype );
var scooty = new Scooter();

更多细节在我的github维基页面上。