数组内忽略数组作用域的函数



我有一个构造函数,我试图有一个函数数组内的原型,但我需要的函数有由构造函数创建的对象的范围,而不是数组的范围。我尝试使用。bind(this)或。bind(_p),但"this"是节点服务器的范围,而_p只是没有变量的原型。

function BoardModel() {
    this.x = 3
    this.y = 2
}
_p = BoardModel.prototype;
_p.skillFunctions = [
    function(){
        console.log(this.x); //undefined
    },
    function(){
        console.log(this.y); //undefined
    },
];

为什么不为每个属性使用自己的方法,而不是一个数组?

function BoardModel() {
    this.x = 3
    this.y = 2
}
_p = BoardModel.prototype;
_p.skillFunctionsX = function (){
    console.log(this.x);
};
_p.skillFunctionsY = function (){
    console.log(this.y);
};
var item = new BoardModel;
item.skillFunctionsX();
item.skillFunctionsY();

箭头函数从封闭上下文使用这个,那么这个如何(双关语)?

function BoardModel() {
    this.x = 3
    this.y = 2
    this.skillFunctions = [
       () => { console.log(this.x) },
       () => { console.log(this.y) },
    ];
}
let board = new BoardModel()
board.skillFunctions.forEach((skillFunction) => { skillFunction() })

最新更新