this 的指向问题
-
this是一个根据使用环境自动取值的特殊的标识符
-
1全局中this为window,没用
console.log(this) 指向window 没有任何意义
-
2函数中使用this
-
普通调用的函数 - this指向 window没用
-
方法调用的函数 - 函数调用者(当前对象) - 非常常用
-
var obj = { name: 'Jack', age: 18, eat: function () { console.log(this); //指向当前对象obj } } obj.eat();
-
3构造函数中的this - 指向new创建的对象
-
function Createobj(name, age) { console.log(this); this.name = name, this.age = age; this.eat = function () { console.log('ice cream'); } } var obj1 = new Createobj('Jack', 18);
-
4 事件中的this
-
事件是方法结构,内部的this指向事件源,以后事件中统一使用this操作即可