JavaScript基础知识 005---this指向

120 阅读1分钟

1.1 作用

为当前的变量或方法提供指向

1.2 具体指向

1.2.1 全局

console.log(this)	//Window 

1.2.2 对象内部

const obj = {
    a:1,
    add () {
        return this.a;
    }
};

console.log(obj.add()); // 1   指向当前对象
const add = obj.add;
console.log(add()); // NaN	

1.2.3 构造函数

function Fun() {
    this.a = 10;
}
const fun = new Fun();
console.log(fun.a); // 10  绑定到当前实例对象上

1.2.4 箭头函数

箭头函数没有this,指向上一层作用域

function Fun() {
    this.a = 10;
    this.method = function() {
        setTimeout(() => {
            console.log(this); // Fun {a: 10, method: ƒ}	
        }, 1000);
    }
}

const fun = new Fun();
fun.method();

1.2.5 事件上

<button onclick="console.log(this)">按钮</button> // 指向该DOM节点

如果觉得有帮助欢迎点赞、评论。 上述内容仅仅代表个人观点,如有错误,请指正。如果你也对前端感兴趣,欢迎访问我的个人博客sundestiny.github.io/myblog/