我如何从父调用原型子方法

How can I call prototype child method from parent

本文关键字:调用 原型 子方法      更新时间:2023-09-26

我想调用子对象方法form prototype object:

function Hamster() {
    this.sleep = function(){
      console.log('sleep');
    }
}
Hamster.prototype = new function(){
    var _self = this;
    this.test = function(){
      this.sleep();
      //_self.sleep(); //not working
    }
}
lazy = new Hamster();
lazy.test();

为什么当我使用this.sleep()一切工作正常,但当我使用_self.sleep() (_self变量有this值)我得到错误?为什么test()函数里面的_selfthis不一样?

让我们用一个返回两个东西的函数来编写它,让我们更容易比较它们

function Constructor() {}
Constructor.prototype = new function () {
    var foo = this;
    this.bar = function () {
        return {"this": this, "foo": foo};
    };
};
var instance = new Constructor(),
    o = instance.bar();

现在测试我们得到的

o.this === instance; // true
o.foo === instance; // fase
// so what is o.foo ?
o.foo === Constructor.prototype; // true

这告诉我们什么?

  • 当我们从instance调用方法时,this引用该实例
  • 当我们用new调用一个函数时,this指的是new创建的一个新的对象实例;在本例中,它是我们为Constructor
  • 设置的原型对象

何时设置这些引用?

  • instance.bar中的this仅在实际调用instance.bar时设置
  • new function () { ... }中的this在创建时立即设置,并且之后不会更改(您基本上使用了IIFE),这也是new返回的内容,因此Constructor.prototype在此示例中设置为

存储在self中的this引用与您在分配给test()的匿名函数中调用的this引用不同。关键是,您正在创建并分配给Hamster.prototype的函数的this作用域是一个空对象。这是因为你使用了new关键字。

Hamster.prototype = new function(){
    //Stores the reference to the empty object that's the scope of the anonymous 
    //function because it was called using the new keyword.
    var _self = this; 
    this.test = function(){
      //Works because the this keyword is a reference to Hamster.
      this.sleep(); 
      //Does not work because the empty object doesn't have a sleep method.
      //_self.sleep(); 
    }
}

你对原型的工作方式感到困惑。

你可能只想要

Hamster.prototype = {
    test: function() {
        this.sleep();
    }
};

你所做的是为原型创建一个新对象。您正在设置的_self变量不是指向单个仓鼠对象的this,而是指向您正在创建的新原型对象的this,该对象丢失在世界中。

_self是您定义的匿名函数之外的一个局部变量并且您没有传递它所以它没有在

中定义