为什么我们在此代码段中使用了"this"关键字?

Azi*_*nam 0 javascript oop object this code-snippets

    var someObject = {
someArray : new Array(),

someInt : 0,

Total: function(){

this.someInt = 0;//we used "this" keyword here, why?Cant we just say "someInt = 0"?

for(var i=0;i<this.someArray.length;i++){//and here..

var c = this.someArray[i];//again we use "this"

this.someInt += c.value;//also here
}
Run Code Online (Sandbox Code Playgroud)

那么为什么我们使用"this"关键字呢?我们只能输入变量的名称?

Ada*_*man 5

this关键字是指代为如果你这样调用该函数的调用时以后,即对象:

someObject.Total()
Run Code Online (Sandbox Code Playgroud)

然后this将参考someObject函数内部.由于this关键字,该功能可以修改someInt和读取someArray成员someObject.如果this从函数体中删除,那么所有这些引用都将是全局变量或函数体本地的变量.