<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>函數(shù)中的this</title>
</head>
<body>
</body>
<script>
//寫一個對象诱桂,對象中的函數(shù)叫方法,或者類方法
//對象里this指向的問題,構造函數(shù)同理
let hxj={
name:"haoxuejie",
//對象的方法里想用到對象里的變量或其他方法畴椰,這是就要加this,
//this只的是當前對象的引用
show:function(){
console.log(this);//this指向當前對象{name: "haoxuejie", show: ?}
console.log(this.name);
},
//但是如果對象的方法b里又定義了函數(shù)c,那這個函數(shù)c里的this指針指向window
b:function(){
let _this=this;
console.log(this);//{name: "haoxuejie", show: ?, render: ?}
function c(){
//Window {postMessage: ?, blur: ?, focus: ?, close: ?, frames: Window, …}
console.log(this);
//如果我在這個函數(shù)c里面想訪問對象的name弃舒,在c()外面b里面就先存一下this
console.log(this.name);//空癞埠,因為window里也有一個name的屬性
console.log(_this.name);//haoxuejie
}
c();
}
};
//hxj.show();//haoxuejie
//全局環(huán)境this就是指向window
//console.log(window);//Window {postMessage: ?, blur: ?, focus: ?, close: ?, frames: Window, …}
//console.log(this);//Window {postMessage: ?, blur: ?, focus: ?, close: ?, frames: Window, …}
//console.log(this==window);//true
hxj.b();
</script>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>箭頭函數(shù)與this</title>
</head>
<body>
</body>
<script>
let lesson={
site:"后盾人",
lists:['js','css','mysql'],
show:function(){
const self=this;
return this.lists.map(function(list){
console.log(this);//指向window
return `${self.site}-${list}`;
});
},
show0:function(){
const self=this;
return this.lists.map((list)=>{
//使用箭頭函數(shù)可以使函數(shù)內(nèi)部的this指向與外部一致
console.log(this); //指向lesson
return `${this.site}-${list}`;
});
},
};
//console.log(lesson.show());
lesson.show();
lesson.show0();
console.log(lesson.show());
console.log(lesson.show0());
</script>
</html>