<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>构造函数里的this指向</title>
</head>
<body>
<script>
/*
* this 在面向对象里面的this 构造函数里面的this在构造函数里面,
* 当new 函数的时候,这个函数就变成了构造函数this单一的就是指向实例化对象
* 但是可以通过call、apply、bind去改变构造函数里的this指向
* */
function Person(){
this.name = 'Tom';
this.age = 20;
this.move = function(){
console.log(this); //指向Person
// play(); //原本指向window
play.call(this); //改变this指向,指向Person
this.eat = function(){
console.log('eat的方法');
console.log(this);
}
}
}
function play(){
console.log(this)
}
var p1 = new Person();
p1.move();
p1.eat();
//必须调用了move()方法后才可以调用eat()方法
/*
* 闭包中的this
* 闭包函数----将方法和变量私有化并公开接口,这个接口就是函数
* */
function closer() {
var abc = 10;
function test1(){
console.log('我是test1');
console.log(this)
}
function test2(){
console.log('我是test2');
console.log(this)
}
return {test1,test2}
}
var test = closer();
console.log(test); //结果是{test1: ƒ, test2: ƒ}
test.test2(); //this指向的仍然是{test1: ƒ, test2: ƒ}
// 练习
console.log('===============');
function closer1(){
function test3(){
console.log('我是test3');
console.log(this); //this指向{test3}
function test4(){
console.log('我是test4');
console.log(this); //this指向window
}
return test4.bind(this) //this指向了{test3}
}
return {test3}
}
console.log(closer1()); //得到的是一个对象 {test3: ƒ}
closer1().test3()();
</script>
</body>
</html>
来源:CSDN
作者:beibei_niao
链接:https://blog.csdn.net/beibei_niao/article/details/104693353