【问题标题】:How to call method of another function without prototyping [duplicate]如何在没有原型的情况下调用另一个函数的方法[重复]
【发布时间】:2017-03-26 16:00:24
【问题描述】:

这肯定是个微不足道的问题,但我对 JavaScript 有点困惑。我想在另一个函数中调用方法。我花了一些时间来处理这个问题,到目前为止我得到的只是第二段代码。我想知道,是否有评论中提到的类似解决方案。

function Student() {
  this.greeting = function() {
    alert('Hi! I\'m student.');
  };
};

function Teacher() {
  Student.call(this)
  this.greeting = function() {
    Student.???  // here I want something like "inherited", or call  Student.greeting()
    alert('and I like apples');
  };
};

我想确定,没有像原型设计这样的其他选择:

function Student() {

};

Student.prototype.greeting = function() {
    alert('Hi! I\'m student.');
  };

function Teacher() {
  Student.call(this);
  this.greeting = function() {
    Student.prototype.greeting();
        alert('and I like apples');
  };
};

感谢

【问题讨论】:

  • 这看起来像你正在尝试使用带有类继承的阴影,这不符合 JavaScript 的精神,它使用原型链来链接对象。通过委托给其他对象(例如使用 Object.create),您可以通过 `[[Prototype]]' 链接访问这些方法。

标签: javascript


【解决方案1】:

Student 是一个函数,在你的情况下它也是一个构造函数。 要调用“学生”,您需要保存调用构造函数学生返回的对象

function Teacher() {
  var stdnt = new Student()
  this.greeting = function() {
    stdnt.greeting()
    alert('and I like apples');
  };
};

此外,在您的代码中 Student.call(this) 相当于只是函数调用 Student() - 无需创建新对象

更新2。从内部函数调用 stdnt 称为“闭包”

【讨论】:

  • 那么唯一的可能就是实例化学生函数?
  • 在你的例子中,greeting 是 student 的成员函数
  • 您的变种除外?是的,您必须通过调用 Student 构造函数来实例化新对象。当然可能还有其他方式,例如像这样
  • “调用”函数将从学生那里获取属性(现在没有),然后我可以在教师中使用它们。但是我不能对函数(方法)做同样的事情......这令人沮丧......
  • var Student = {greeting: function (){alert("Student"}}
猜你喜欢
  • 2011-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-01
  • 2022-06-18
  • 2022-01-08
  • 2012-02-13
  • 1970-01-01
相关资源
最近更新 更多