EventEmitter.call()做什么? [英] What does EventEmitter.call() do?

查看:306
本文介绍了EventEmitter.call()做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这个代码示例:

I saw this code sample:

function Dog(name) {
    this.name = name;
    EventEmitter.call(this);
}

它从EventEmitter继承,但call()方法实际上是什么吗?

it 'inherits' from EventEmitter, but what does the call() method actually do?

推荐答案

基本上, Dog 应该是带有属性的构造函数名称 EventEmitter.call(this),在 Dog 实例创建期间执行时,附加从<$ c $声明的属性c> EventEmitter 构造函数到 Dog

Basically, Dog is supposedly a constructor with a property name. The EventEmitter.call(this), when executed during Dog instance creation, appends properties declared from the EventEmitter constructor to Dog.

请记住:构造函数仍然是函数,并且仍然可以用作函数。

Remember: constructors are still functions, and can still be used as functions.

//An example EventEmitter
function EventEmitter(){
  //for example, if EventEmitter had these properties
  //when EventEmitter.call(this) is executed in the Dog constructor
  //it basically passes the new instance of Dog into this function as "this"
  //where here, it appends properties to it
  this.foo = 'foo';
  this.bar = 'bar';
}

//And your constructor Dog
function Dog(name) {
    this.name = name;
    //during instance creation, this line calls the EventEmitter function
    //and passes "this" from this scope, which is your new instance of Dog
    //as "this" in the EventEmitter constructor
    EventEmitter.call(this);
}

//create Dog
var newDog = new Dog('furball');
//the name, from the Dog constructor
newDog.name; //furball
//foo and bar, which were appended to the instance by calling EventEmitter.call(this)
newDog.foo; //foo
newDoc.bar; //bar

这篇关于EventEmitter.call()做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆