gpt4 book ai didi

javascript - 嵌套函数中的“this”

转载 作者:行者123 更新时间:2023-12-01 13:53:42 25 4
gpt4 key购买 nike

   var EventEmitter = require('events').EventEmitter;
var Counter = function (init) {
this.increment = function () {
init++;
this.emit('incremented', init);
}
}
Counter.prototype = new EventEmitter();
var counter = new Counter(10);
var callback = function (count) {
console.log(count);
}
counter.addListener('incremented', callback);

counter.increment(); // 11
counter.increment(); // 12

在上面的示例中,this.increment 中的this 是指计数器对象。 this.emit 中的 this 指的是什么?它是增量对象还是计数器? emit 究竟是如何执行的?

最佳答案

当您直接在 Object.prototype 上定义任何内容时,它会被所有对象继承。也许代码的任何地方都有这样的定义:

Object.prototype.emit = function(stringValue, function(){});

关于javascript - 嵌套函数中的“this”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34056484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com