2015-11-05 39 views
0
const mongoose = require("mongoose"), 
requiredAttr = {type: String, required: true}, 
employeeSchema = new mongoose.Schema({ 
     employeeNumber: { 
      type: String, 
      unique: true, 
      required: true 
     }, 
     firstName: requiredAttr, 
     lastName: requiredAttr, 
     image: requiredAttr 
    }, 
    { 
     timestamps: true //get createdAt, updatedAt fields 
    }); 

employeeSchema.methods.writeThis =() => { 

    console.log("doing writeThis"); 
    console.log(this); 
}; 

module.exports = mongoose.model("Employee", employeeSchema); 

始终产生猫鼬实例方法失去执行上下文

doing writeThis 
{} //would think I would see my employee properties here 

然后我测试一些基本的上下文经由节点命令行切换,并找到我不能执行以下操作(如在浏览器中)

let test = { foo: "bar" }; 
let writeThis =() => { console.log(this); }; 
writeThis.apply(test); //or 
writeThis.bind(test); 

我错过了什么?

回答

1

功能和方向的语法是不能直接互换:

let writeThisArrow =() => { 
    console.log(this); 
}; 
writeThisArrow.call({stuff: "things"}); 
// {} 

function writeThisFunction() { 
    console.log(this); 
} 
writeThisFunction.call({stuff: "things"}); 
// {stuff: "things"} 

在函数语法,调用this引用它就是所谓的上下文。在Arrow语法中,调用this引用它定义的上下文。在使用猫鼬的情况下,它是文件本身的实际this。例如:

exports.stuff = "things"; 

let writeThisArrow =() => { 
    console.log(this); 
}; 
writeThisArrow.call(); 
// {stuff: "things"} 

this” 箭头语法是一成不变的,使用bind()call(),或apply()你不能注入上下文。在你的情况,只需切换回标准函数声明,你会没事的。

编辑:我用错了措辞。 this不是在箭头语法中不可变的,您只能通过应用程序更改上下文。完全

exports.stuff = "things"; 
let writeThisArrow =() => { 
    console.log(this); 
}; 
writeThisArrow.call(); 
// {stuff: "things"} 

exports.otherStuff = "other things"; 
writeThisArrow.call(); 
// {stuff: "things", otherStuff: "other things"} 
+0

它:但是,您可以通过编辑它被定义的情况下改变它!感谢您及时的回复 –