JavaScript改变this指向的三种方法
1.call() 方法call()可以改变函数内的this 指向,可以调用函数<script>function Person() {this.name = 'kobe';this.sex = '男';this.age = '41'}function Star(name,sex,age) {Person.call(th..
·
1.call() 方法
call() 可以改变函数内的this 指向,可以调用函数
<script>
function Person() {
this.name = 'kobe';
this.sex = '男';
this.age = '41';
}
function Star(name,sex,age) {
Person.call(this,name,sex,age); //call 改变了this指向
console.log(this.name);
console.log(this.sex);
console.log(this.age);
}
new Star(); // 实例化对象
</script>
2. apply() 方法
apply() 方法可以改变this指向,也会调用函数 和 call() 不同点是 apply() 的参数必须是数组或者伪数组的形式
<script>
function Person() {
this.name = 'kobe';
this.sex = '男';
this.age = '41';
}
function Star(arr) {
console.log(this); // 这个this指向 Star
console.log(arr);
}
Star.apply(Person,['科比']) // 改变this指向之后,变成指向Person ,且参数要是数组形式
</script>
3. bind() 方法
bind() 方法 可以改变this指向,但不会调用原来的函数,返回的是改变this指向之后的产生的新函数
<script>
function Person() {
this.name = 'kobe';
this.sex = '男';
this.age = '41';
}
function Star(a,b) {
console.log(this);
console.log(a + b);
}
var fn = Star.bind(Person,1,3); // 不会调用原来的函数,产生一个新的函数(this指向改变的新函数)
fn();
</script>
更多推荐
已为社区贡献1条内容
所有评论(0)