gpt4 book ai didi

javascript - 为什么 'this' 没有采用正确的范围

转载 作者:行者123 更新时间:2023-11-28 01:11:39 25 4
gpt4 key购买 nike

好吧,我知道 Javascript 中有几千个关于 this 范围的奇怪线索(这让人怀疑这种语言是否设计得很好) - 但我仍然无法解释“this”一:

//works
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
this.meow = meow }
}
var MyCat = new Cat()
MyCat.meow()

//works
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
this.meow = function() { alert(this.theCatName + " meow") }
}
var MyCat = new Cat()
MyCat.meow()

//works
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
Cat.prototype.meow = function() { alert(this.theCatName + " meow") }
}
var MyCat = new Cat()
MyCat.meow()

//doesn't work
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
this.meow = function() { meow() } }
}
var MyCat = new Cat()
MyCat.meow()

//doesn't work
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
Cat.prototype.meow = function() { meow() } }
}
var MyCat = new Cat()
MyCat.meow()

现在我的理解是,在后两种情况下 Cat.prototype.meowthis.meow 是恰好调用 meow() 的匿名函数,即Cat() 的内部函数 - 但 this 的上下文清楚地引用了函数内部的 cat - 它会发生什么?

这是一个半规范的答案: See How to access the correct this / context inside a callback?但它仅说明了“this”的实际上下文:

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scope, like other variables.

最佳答案

当您调用对象的方法时,只有当您将其作为对象的成员调用时,它才有效,如果您获取对该函数的引用或将其作为常规函数调用,则上下文不是该对象。只有调用函数的方式决定了上下文,上下文不会被继承,因此如果您从方法调用函数,那么它只是常规函数调用。

示例:

function Dog() {

function bark() {}
this.bark = bark;

this.barkThrice() {
bark(); // function call; context = window
this.bark(); // method call; context = the object
var b = this.bark;
b(); // function call; context = window
}

}

要将函数作为对象的方法调用,您需要使用 call method (或bindapply)设置调用的上下文:

function Cat() { 
this.theCatName = "Mistigri";
function meow() { alert(this.theCatName + " meow"); }
this.meow = function() { meow.call(this); };
}
var MyCat = new Cat();
MyCat.meow();

演示:http://jsfiddle.net/k6W9K/

关于javascript - 为什么 'this' 没有采用正确的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24354122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com