this基本情况:
1.函数形式调用:window
2.方法的形式调用:调用的方法
3.构建函数:新创建的对象
4. call和apply调用:指定的对象
<script>
/* 怎么理解函数内部this的指向 */
/* tips:this取什么值,是在函数执行的时候确定,而不是定义时确定 */
/* 1.普通函数中的this --指向window*/
function go(){
console.log(this);
}
</script>
<button id="btn">btn</button>
<script>
var btn = document.getElementById("btn");
btn.onclick = function(){
setTimeout(function(){
console.log(this); //window
},500)
}
</script>
<script>
/* 2. 作为对象的方法调用 */
/* 3.在箭头函数中this */
var name = "window"
var obj = {
name:"javascript",
sayName(){
console.log(this.name); //javascript
},
wait(){
console.log(this.name);//javascript
setTimeout(function(){
console.log(this.name); //window
},500)
},
delay(){
setTimeout(()=>{
console.log(this.name); //javascript
})
},
layout(){
setTimeout(function(){
console.log(this.name);
}.bind(this)) //bind改变函数关键字
},
print(){
var that = this;
setTimeout(function(){
console.log(this.name); //javascript
}.bind(that))
}
}
obj.sayName();
obj.wait();
obj.delay();
obj.delay();
obj.print()
</script>
<script>
/*4. call,apply,bind */
function fn1(){
console.log(this);
}
var obj = {
name:"vue"
}
fn1();
fn1.call(obj);
var fn2 = fn1.bind(obj);
fn2();
</script>
<script>
/* 5.class this */
/* 在class类和构造函数中this指向使用new关键字实例化的对象 */
class Person{
skill ="lisi";
constructor(name,age){
this.name = name;
this.age = age
}
}
var p = new Person("lisi",18);
console.log(p.name);
</script>