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

标签 javascript scope

好吧,我知道 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/

相关文章:

javascript - JQuery持续发送AJAX请求

javascript - React - 来自字符串的动态属性

JavaScript 未分配给全局变量

javascript - jQuery javascript 作用域问题

javascript - 使用 JavaScript 使用 htmlOutput 元素作为导出的 PNG 文件的名称

javascript - 从类型 ="button"切换到 asp :LinkButton

javascript - ngResource 使用 $delete 从查询对象中删除记录

c# - 在这种情况下,R 和 C# 的作用域规则有何不同?

javascript - Appcelerator titan - 传递js变量

javascript - 对象创建期间的“this”上下文