其他分享
首页 > 其他分享> > 改变this指向了解一下

改变this指向了解一下

作者:互联网

首先呢,我们知道return可以改变this指向

function Fn(name){
this.name=name;
return {};//undefined,改变了this的指向,指向该未定义对象
}
var fn=new Fn(“maomin”);
console.log(fn.name);

另一种是我们常用的方法,就是给将this赋值给一个变量。

function fn1(age) {
var that=this;
that.age=age;
console.log(this.age)//21
}
fn1(“21”);

但是上面的方法太low了。
接下来我们说一下关于改变this指向的三种高大上方法:

call()
(1)可以改变匿名函数this指向

var box=document.querySelector("#box");
box.onclick = function(){
  (function(){
    console.log(this); //box
  }).call(this);
};

(2)可以继承方法

function Fn8(name,girlfriend) {
this.name=name;
this.girlfriend=girlfriend;
}
function Fn9(name,girlfriend) {
Fn8.call(this,name,girlfriend);//第一个传的是一个对象,就是你要借用的那个对象,除了第一个参数后面的参数将作为实际参数传入到函数中。
console.log(this.name,this.girlfriend);//maomin, xqm
}
var fn9=new Fn9(“maomin”,“xqm”);

更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/120127993

标签:function,console,name,指向,改变,了解,girlfriend,log
来源: https://www.cnblogs.com/wangchuanxinshi/p/16554634.html