JS-this
Posted yangjiale
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS-this相关的知识,希望对你有一定的参考价值。
JS-this
call,apply,bind作用
call,apply,bind都是用来改变this的指向
使用例子
call的使用
function Person()
alert(this.name);
var student=
name:"zhangShan"
;
Person.call(student); //this指向student,输出zhangShan
apply和call的区别
var person=
name:"zhangShan",
say:function(age,phone)
alert(this.name+" "+age+" "+phone);
;
var person2=
name:"xiaoMing"
;
person.say.call(person2,20,"12356985"); //值必须分开传递
person.say.apply(person2,[20,"12356985"]); //必须是一个数组
var person2Args=[20,"12356985"]; //也可以单独声明然后用apply
bind和call的区别
function Person()
alert(this.name);
var student=
name:"zhangShan"
;
Person.call(student); //直接运行输出结果
Person.bind(student); //不会运行,返回的是一个函数
Person.bind(student)(); //调用函数则运行
var StudentMethod=Person.bind(student); //作为函数保存起来
this绑定
默认绑定
全局环境
console.log(this); //输出window
函数调用
function pd()
console.log(this==window);
pd(); //输出true,函数里的额this被默认绑定window
被嵌套函数独立调用
var a=0;
function test()
var a=1;
function t1()
console.log(this.a); //输出0,this指向window
t1();
test();
上面4-7行等价于:
//IIFE形式
(function t1()
console.log(this.a);
)();
隐式绑定
var a=0;
var test=
a:1,
fun:function()
console.log(this.a);
;
test.fun(); //this隐式绑定到test,输出1
隐式丢失
隐式丢失总结起来只有一种情况:一个对象的方法被独立调用时会造成隐式丢失
函数别名
var a=0;
var test=
a:1,
fun:function()
console.log(this.a);
;
var f=test.fun; //f仅仅等于独立的fun方法,所以this丢失绑定对象,转为默认绑定(绑到window)
f(); //输出0
函数作为参数传递
var a=0;
var test=
a:1,
fun:function()
console.log(this.a);
;
function run(fun)
fun();
run(test.fun); /输出0
内置函数
//将上面代码的8-11行改为内置的setTimeout函数同样会引起隐式
setTimeout(test.fun,0); //输出0
显示绑定
使用call,apply,bind绑定的即为显示绑定
另外还有一些自带对象的某些方法也有显示绑定功能:
例如数组的 map()、forEach()、filter()、some()、every() 方法
例子:数组的forEach()显示绑定
var a=0;
function say()
console.log(this.a);
var obj=
a:1
;
[1,2,3].forEach(say,obj); //参数一:遍历对象,参数二:显示绑定的对象
new绑定
ction person(name,age,phone)
this.name=name; //this指向新创建的对象
this.age=age;
this.phone=phone;
var p1=new person("sam",20,"1256315");
构造函数中,this指向新创建的对象
以上是关于JS-this的主要内容,如果未能解决你的问题,请参考以下文章