学习Nodejs& ES6在某些时候停滞不前

时间:2017-09-19 14:43:47

标签: javascript node.js ecmascript-6

以下是ES6 method.call()方法,它给出了错误

 var obj = {
            name: "Hello ES6 call",
            greet: function(somedata) {
                this.somedata = somedata
                console.log(this.somedata)  //somedata works
                console.log(somedata) //somedata works
                console.log(`Hello ${ this.somedata } `) 

//Error this.somedata undefined
        }
    }

    obj.greet.call({name:"from call"},"somedata");

使用ES6模板文字未定义this.somedata

//second question
var Emitter = require("events");
var util = require("util");

function Greetr() {
    this.greeting = "greetr function ";
    this.greet = function(data) {
        console.log(this.greeting, data)
        this.emit('greet', data);
    }
}

util.inherits(Greetr, Emitter);
var greeter1 = new Greetr();

greeter1.on('greet', function(data) {
    console.log("greet on", data);
});

greeter1.greet(" some data"); //works
greeter1.greet.call({greeting:"greeting call function"}, "call data")

this.emit未定义为什么有任何出路使用call()函数

1 个答案:

答案 0 :(得分:-1)

当您致电greeter1.greet.call({greeting:"greeting call function"}, "call data")时,您明确告诉其使用{greeting: "greeting call function"}作为this。所以当它调用this.emit时,它是未定义的,因为你已经告诉它是未定义的。

我建议你不要明确定义this使用这种策略,但是如果它真的是你想要做的,那么你必须在你传递的对象中添加一个emit函数in。我认为你希望greeter1成为发射的东西,即使你传递了不同的物体?如果是这种情况,那么您可能需要这样做:

greeter1.greet.call({
    greeting:"greeting call function",
    emit: greeter1.emit.bind(greeter1)
}, "call data");

同样,我建议不要这样做。我认为接受问候作为函数参数(可能具有默认值)并且不依赖于劫持this

会更好
var Emitter = require("events");
var util = require("util");

function Greetr() {
    this.greet = function(data, greeting = "greetr function") {
        console.log(greeting, data)
        this.emit('greet', data);
    }
}

util.inherits(Greetr, Emitter);
var greeter1 = new Greetr();

greeter1.on('greet', function(data) {
    console.log("greet on", data);
});

greeter1.greet(" some data");
greeter1.greet("call data", "greeting call function");