js中this用法(1)
来源:互联网 发布:阿里云 sap hana 编辑:程序博客网 时间:2024/06/06 02:07
this的用法非常的单一,因为他们没有js特有的动态绑定。
function funcA() { this.name = "hello"; console.log(this.name); this.show = function() { console.log(this.name); }}funcA();// 1、hellovar a = new funcA();//2、helloa.show();//3、hellovar objA = { name: "objA"}a.show.call(objA);//4、objAvar objB = { name: "objB"}objB.show = a.showobjB.show();//5、objB(objB.show = a.show)();//6、hello、
控制台打印
这几段代码就把this常见的情况给表现出来的差不多了, this在js中主要有四种用法:
1、作为普通函数使用
2、作为对象方法来使用
3、call和apply
4、作为构造函数来使用
下面分别说明
1、作为普通函数来使用:
function funcA() { this.name = "hello"; console.log(this.name); this.show = function() { console.log(this.name); }}funcA();// 1、hello
这个代码很简单,但也隐藏了一个坑,就是这个时候的this 代表的是window的指针,所以当这段代码运行完之后,你再输出 console.log(window.name)时候,你会发现输出为”hello”,在使用中尽量避免。
2、作为对象方法来使用
var obj={name:"hello",show:function(){
console.log(this.name);
}};
obj.show();
这个很简单,this指向自己,所以this.name就用hello;
如果代码修改下:
var obj={name:"hello",show:function(){ console.log(this.name);}};obj.show();var objA={name:"world"}objA.show=obj.show;objA.show()
这个结果又是什么呢?答案是”world”,因为在js中对象都是引用类型,当objA.show=obj.show这句代码把objA.show也指向的show方法,所以在调用的时候会把this,指向objA而不是obj.
3、call和apply
这个在上面的继承中的原型冒充中也提过一些,这里也详细说明this在call和apply中微秒的用法:
function funcA() { this.name = "hello"; console.log(this.name); this.show = function() { console.log(this.name); }} var a = new funcA();a.show();var objA = { name: "objA"}a.show.call(objA);
上面这段代码就是call的用法,这里我们可以把代码拆解成我们能看的懂的形式:
a.show.call(objA)====>{obj.show=a.show();obj.show();delete obj.show();}
上面就是call的类似执行的过程的形势(实际上并不是这样的,可以这样来记),知道了这个执行过程,我们就来探究这个的执行过程:
1、把a.show里面的方法中的this全部换成obj.
2、执行a.show(),同时把后面的参数作为参数处理。
4、作为构造函数来使用
function funcA(name){ this.name; this.show=function(){ console.log(name); }}var a=new funcA("hello");a.show();
作为构造函数使用的时候,在new的关键字创建对象的时候,会先生成一个空对象,然后调用方法,把this的替换成这个空对象。(这个在上篇有详细的说明,这里不多说)。在创建对象的时候,this指针就指向了创建新对象。
唯一的有一个(objB.show = a.show)();这个比较奇怪,因为赋值的时候,返回的是右边的那个函数,所以最终执行的也是a.show();- js中this用法(1)
- js中this用法
- Js中this用法
- js中this用法详解(2)
- js 中 this 的用法
- js中this的用法
- js中this的用法
- js中this的用法
- js中this的用法
- JS中this的用法
- js中this的用法
- js中this的用法
- js中this的用法
- js中this的用法
- JS中THIS的用法
- js中this的用法
- js中this的用法
- js中this的用法
- Spring-boot-devtools依赖 极大程度上方便了开发者
- JavaScript学习笔记_AMD规范
- 数列极差和大数模板
- 双异或
- 二级结构体快排
- js中this用法(1)
- Ubuntu 上安装画流程图工具Dia
- BFS 模板
- 通过IP地址连接SQL Server2012 服务器
- 集成开发环境pycharm开发opencv项目
- 1232 畅通工程
- gflags(google开源的一套命令行参数解析工具)
- C# Bitmap图像处理(含增强对比度的三种方法)
- 1829 A Bug's Life