关于js中的this的指向问题

来源:互联网 发布:硬件温度监控软件 编辑:程序博客网 时间:2024/05/24 06:09

1.全局代码中的 thisalert(this)//window全局范围内的 this 将会指向全局对象,在浏览器中即使 window

2.作为单纯的函数调用 function fooCoder(x) { this.x = x; } fooCoder(2); alert(x);// 全局变量 x值为2 这里 this 指向了全局对象,即 window。在严格模式中,则是 undefined

3.作为对象的方法调用
var name = “clever coder”;
var person = {
name : “foocoder”,
hello : function(sth){
console.log(this.name + ” says ” + sth);
}
}
person.hello(“hello world”);
输出 foocoder says hello world。this 指向 person 对象,即当前对象。

4..作为构造函数
new FooCoder();
函数内部的 this 指向新创建的对象

5.内部函数
var name = “clever coder”;
var person = {
name : “foocoder”,
hello : function(sth){
var sayhello = function(sth) {
console.log(this.name + ” says ” + sth);
};
sayhello(sth);
}
}
person.hello(“hello world”);//clever coder says hello world
在内部函数中,this 没有按预想的绑定到外层函数对象上,而是绑定到了全局对象。这里普
遍被认为是 JavaScript 语言的设计错误,因为没有人想让内部函数中的 this 指向全局对象。
一般的处理方式是将 this 作为变量保存下来,一般约定为 that 或者 self:
var name = “clever coder”;
var person = {
name : “foocoder”,
hello : function(sth){
var that = this;
var sayhello = function(sth) {
console.log(that.name + ” says ” + sth);
};
sayhello(sth);
}
}
person.hello(“hello world”);//foocoder says hello world