2015-11-05 54 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

它:但是,您可以通過編輯它被定義的情況下改變它!感謝您及時的回覆 –