您的位置:首页 > Web前端 > JavaScript

javaScript中的this的使用

2016-06-22 16:37 387 查看
1) 函数有所属对象时:指向所属对象

var myObject = {value: 100};
myObject.getValue = function () {
console.log(this.value); // 输出 100

// 输出 { value: 100, getValue: [Function] },
// 其实就是 myObject 对象本身
console.log(this);

return this.value;
};

console.log(myObject.getValue()); // => 100


2) 函数没有所属对象:指向全局对象

var myObject = {value: 100};
myObject.getValue = function () {
var foo = function () {
console.log(this.value) // => undefined
console.log(this);// 输出全局对象 global
};

foo();

return this.value;
};

console.log(myObject.getValue()); // => 100


3) 构造器中的 this:指向新对象

var SomeClass = function(){
this.value = 100;
}

var myCreate = new SomeClass();

console.log(myCreate.value); // 输出100


4) apply 和 call 调用以及 bind 绑定:指向绑定的对象,通过 apply 或 call 或 bind 来改变 this 的所指

var myObject = {value: 100};

var foo = function(){
console.log(this);
};

foo(); // 全局变量 global
foo.apply(myObject); // { value: 100 }
foo.call(myObject); // { value: 100 }

var newFoo = foo.bind(myObject);
newFoo(); // { value: 100 }


这是链接地址

上面就是Java的this的四种使用方式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript 对象 函数