为什么在大多数示例中 'this' 时创建新变量
why new variable is created when 'this' in most of the examples
我正在阅读 tutorial 的 AngularJS。我不知道他们为什么要为使用 'this' 关键字声明新变量。没有那个 new 关键字,我们可以使用 'this' 而没有 new variable(self)。
function TestCtrl() {
var self = this;
self.people = [
{
name: "Eric Simons",
born: "Chicago"
},
{
name: "Albert Pai",
born: "Taiwan"
},
{
name: "Matthew Greenster",
born: "Virginia"
}
];
}
angular.module('app', [])
.controller('TestCtrl', TestCtrl);
有什么不同吗?
this
的上下文根据您使用它的地方而变化。
controller('myController', function() {
var a = this;
$myElement.each(function(){
var b = this;
})
})
在上面的例子中,this
在使用它们的地方的上下文是不同的。
有时可能需要保存对 this
的引用,以便在其他地方使用它。
在您提供的示例中,将 this
分配给变量不是必需的,但通常按照约定完成,因为它可以提高代码的可读性。
this
所指的对象根据其使用范围而变化。通过将它分配给特定范围内的变量,您可以固定该对象,以便您可以在子范围内引用它。
您没有使用任何子作用域,因此您可以直接引用 this
。
我正在阅读 tutorial 的 AngularJS。我不知道他们为什么要为使用 'this' 关键字声明新变量。没有那个 new 关键字,我们可以使用 'this' 而没有 new variable(self)。
function TestCtrl() {
var self = this;
self.people = [
{
name: "Eric Simons",
born: "Chicago"
},
{
name: "Albert Pai",
born: "Taiwan"
},
{
name: "Matthew Greenster",
born: "Virginia"
}
];
}
angular.module('app', [])
.controller('TestCtrl', TestCtrl);
有什么不同吗?
this
的上下文根据您使用它的地方而变化。
controller('myController', function() {
var a = this;
$myElement.each(function(){
var b = this;
})
})
在上面的例子中,this
在使用它们的地方的上下文是不同的。
有时可能需要保存对 this
的引用,以便在其他地方使用它。
在您提供的示例中,将 this
分配给变量不是必需的,但通常按照约定完成,因为它可以提高代码的可读性。
this
所指的对象根据其使用范围而变化。通过将它分配给特定范围内的变量,您可以固定该对象,以便您可以在子范围内引用它。
您没有使用任何子作用域,因此您可以直接引用 this
。