小编n0m*_*rcy的帖子

7
推荐指数
1
解决办法
1842
查看次数

Javascript在分配给其他变量时丢失了上下文

为什么在javascript中如果将对象方法引用到某个变量,则会丢失该对象上下文.无法找到任何链接,解释引擎盖下发生的事情.除了这个说明: 'this'指的是'拥有'不接缝为真的方法的对象.

var Class = function() {
    this.property = 1
}

Class.prototype.method = function() {
    return this.property;
}

var obj = new Class();
console.log(obj.method() === 1);

var refToMethod = obj.method; // why refToMethod 'this' is window


console.log(refToMethod() !== 1) // why this is true?

var property = 1;
console.log(refToMethod() === 1)
Run Code Online (Sandbox Code Playgroud)

javascript this

5
推荐指数
1
解决办法
514
查看次数

标签 统计

.net ×1

c# ×1

javascript ×1

punctuation ×1

regex ×1

this ×1