首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >EventEmitter.call()做了什么?

EventEmitter.call()做了什么?
EN

Stack Overflow用户
提问于 2013-02-23 20:50:19
回答 2查看 10.8K关注 0票数 26

我看到了这个代码示例:

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

它“继承”自EventEmitter,但是call()方法到底做了什么呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-23 20:57:06

基本上,Dog应该是一个具有name属性的构造函数。在创建Dog实例期间执行EventEmitter.call(this)时,它会将从EventEmitter构造函数声明的属性追加到Dog

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

//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
票数 69
EN

Stack Overflow用户

发布于 2015-12-23 03:56:22

EventEmitter.call(this);

这一行大致相当于在具有经典继承的语言中调用super()。

票数 27
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15040717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档