/**普通函数的this指向
* this指向调用该函数的那个对象**/
let bird = {
name:'jiji',
sayName(){
console.log(this.name);
}
}
bird.sayName();
/**构造函数中的this指向实例化的那个对象**/
/**ES5 */
function Bird1(name){
this.name = name;
}
var bird1 = new Bird1('jiji');
console.log(bird1.name);
/**ES6 */
class Bird2{
constructor(name){
this.name = name;
}
}
let bird2 = new Bird2('jiji');
console.log(bird2.name);
/**DOM事件中的this指向触发事件的DOM对象 */
<body>
<button>按钮</button>
</body>
let btn = document.querySelector('button');
btn.onclick = function {
console.log(this);//指向button
}
/**全局对象中的this */
console.log(this);//this指向window对象
function fun(){
console.log(this);//也是指向window对象
}
fun();//完整写法是window.fun()
/**如何改变this指向,使其指向定义的对象呢? */
/**ES5:把this赋值给self */
/**ES6:用箭头函数 */
let dog = {
name:'wangwang',
sayName(){
let self = this;
console.log(this);
setTimeout(function(){
console.log(self.name);
},1000)
}
}
dog.sayName();
/**ES6 */
/**补充:箭头函数的this指向的是它所在的上下文 */
let dog1 = {
name:'wangwang',
sayName(){
setTimeout(()=>{
console.log(this.name);
},1000);
}
}
dog1.sayName();
You辉编程_彻底帮你搞懂JavaScript中的this指向
最新推荐文章于 2024-08-25 09:57:22 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)