在开发过程中,相信大家总会被this指向搞迷糊。接下来将给大家彻底搞明白this指向的问题。
一、首先看this在哪个作用域下,在全局中 this一律指向window
var name = 'aa'
function fn(){
var name = 'bb'
console.log(this.name) //bb fn的作用域是在全局中 所以指向window
}
fn()
二、在函数体中分为接下来几种情况
普通函数调用,谁调用指向谁
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的函数
参一是谁 就指向谁
var name = 'aa'
var wzx = {
name:'wzx',
say:function(){
console.log(this.name)
}
}
wzx.say.apply(this)// aa 指向window