this是状态机,是动态变化的对象,随着作用域的改变而改变 this伴随着作用域的产生而产生 一、首先看this在哪个作用域下,在全局中 this一律指向window
var name = 'aa' function fn(){ var name = 'bb' console.log(this.name) //bb fn的作用域是在全局中 所以指向window } fn()二、在函数体中需要分情况
用new创建实例对象时,this的指向是new 实例的对象
function bar(name){ console.log(this) // 指向 new 实例的对象 this.name = name } var wyh = new bar('王宇航')如果return 返回为对象、数组、函数 ,那么 this 就不指向 new 实例化的对象
function foo(){ // var age = 12 this.name = 'wyh'; console.log(this) // this 为 函数 非对象 return { name:'王宇航' } } var obj = new foo() console.log(obj)//this指向return的对象、数组、函数普通函数调用,谁调用指向谁
var name = '小韩' function foo(){ var name = '小韩18'; var age = 18; console.log(this.name) } var person = { name:'aa', age:25, foo:foo, do:this.name // window } // 谁调用指向谁 仅看函数执行左边最近的对象是啥。 foo() //小韩 person.foo() //aa foo是被执行的事件处理函数 在事件处理函数中this 指向的是【触发事件的元素】,不是绑定事件的元素
// 获取div 元素对象 并赋值给node var node = document.getElementsByTagName('div')[0] // 给node 绑定点击事件 node.onclick = function () { // 事件处理函数 console.log(this) }构造函数 在构造函数中 this指向的是new实例化的对象
//注意:有return的函数一定不是构造函数 function Animal(type, name,color, eat) { //·创建构造函数 this.type = type; //this.对象 也是字符串 this.name = name; //给实例化的对象 添加属性 this.color = color; this.eat = eat; this.do = function(){ // 谁调用指向谁(指的是调用的对象) alert(this.name + '是' + this.color) } } var dog = new Animal('哺乳动物','狗','黑色',function(){ console.log('喜欢吃骨头') }) //实例化对象 new调用的函数就是构造函数若有call apply bind,则根据它们的参数决定this的指向
var name = 'aa' var wzx = { name:'wzx', say:function(){ console.log(this.name) } } wzx.say.apply(this)// aa 指向window1: 先看 this 在哪个作用域中 全局—> this = window 如果在function 函数体中。 2:看函数执行。 2.0: 判断哪一个函数被执行?再看方法体中 this 指向谁? 2.1 看是否有call apply bind ,有—> 参一是谁 this 就指向谁 2.2 看是否是事件处理函数; 是----> 触发事件元素 2.3 调用函数是否是new 是构造函数,this 指向new 实例的对象 2.4 以上都不满足。就是谁调用指向谁。