当前位置:网站首页>改变this指向了解一下
改变this指向了解一下
2022-07-22 21:54:00 【马克社区】
首先呢,我们知道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指向
12var 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
边栏推荐
- LAN SDN technology hard core insider 7 from layer 2 to layer 2
- 实验二 YUV
- 延伸联接边界,扩展业务范围,全面迈向智能云网2.0时代
- 开幕在即 | “万物互联,使能千行百业”2022开放原子全球开源峰会OpenAtom OpenHarmony分论坛
- Flick batch reading es
- LeetCode 第26天
- The boss asked me to do an IP territorial function and an open source library!
- 牛客小白月赛53
- 实验三 LZW
- Worthington纯化酶制剂助力新生儿心肌细胞分离系统研究
猜你喜欢

General, special and hidden attributes of the file (instance generates animation)

Storage structure and method of graph (I)

使用Hystrix实现容错处理

MySQL消息队列表结构

Fault tolerant processing with hystrix

Experiment 4 DPCM

Scala idea prompt function parameters

Mysql A left(right) join B on A.id=B.id and A.age=1与A left(right) join B on A.id=B.id where A.age=1

File upload, server file name Chinese garbled file upload, server file name Chinese garbled

VMware虚拟机更改静态IP和主机名,使用Xshell进行连接
随机推荐
Rust——关于Option详解
6-14漏洞利用-rpcbind漏洞利用
Customize flick es source
LAN SDN technology hard core insider 6 distributed anycast gateway
Kubernetes deployment strategy
主控芯片CSU18M92开发智能体重秤方案
记一次线上SQL死锁事故:如何避免死锁?
Topic domain model
驱动页面性能优化的3个有效策略
Scala idea prompt function parameters
文件的一般、特殊、隐藏属性(实例生动画图)
VMware virtual machine changes static IP and hostname, and uses xshell to connect
matlab声音信号处理 频率图 信号过滤和播放声音
Expérience II Yuv
2022年中国软件产品全国巡回展即将启航
LAN SDN technology hard core insider 7 from layer 2 to layer 2
6-15漏洞利用-smb-RCE远程命令执行
The boss asked me to do an IP territorial function and an open source library!
The Chinese and English dot matrix character display principle of the 111th blog of the fledgling Xiao Li
Web资源共享