前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >改变this指向了解一下

改变this指向了解一下

作者头像
马克社区
发布2022-07-22 20:43:58
2480
发布2022-07-22 20:43:58
举报
文章被收录于专栏:高端IT高端IT

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

function Fn(name){ this.name=name; return {};//?developer/article/2054796/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指向的三种高大上方法:

代码语言:javascript
复制
call()
(1)可以改变匿名函数this指向
12

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

本文系转载,前往查看

如有侵权,请联系?cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系?cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com