js中this关键字的指向

来源:互联网 发布:智能语音拨号软件 编辑:程序博客网 时间:2024/04/28 20:00

在函数执行时,this总是指向调用该函数的对象,有调用对象则指向该对象,无调用对象则指向全局对象window。

1.元素button点击事件函数

btn.onclick = function (event) {    console.log(event); // event指向该点击事件对象    console.log(this); // this指向事件的目标元素,可以访问元素的属性    console.log(this.id);}

2.有对象就指向调用对象

var myObj1 = {value: 1};    myObj1.getValue = function () {    console.log(this.value); // 输出1    console.log(this); // 输出 {value: 1, getValue: function}};myObj1.getValue();

3.没有对象就指向全局对象window

var myObj2 = {value: 1};myObj2.getValue = function () {var foo = function () {    console.log(this.value); // 输出 undefined    console.log(this); // 输出 window对象 // foo虽然定义在getValue函数内,但并没有绑定在任何对象上,故在调用时,指向全局对象window}    foo();    return this.value;}console.log(myObj2.getValue()); // 输出1

4、用new构造函数,指向新对象

var Person = function () {    this.age = 10;};var person1 = new Person();console.log(person1.age);

5.通过apply 或 call 或 bind 来改变this的指向

var myObj3 = {value: 100};var foo = function () {    console.log(this);};foo();foo.apply(myObj3);foo.call(myObj3);var newFoo = foo.bind(myObj3);newFoo();

转载自:http://blog.csdn.net/junbo_song/article/details/52261247