您的位置:首页 > 其它

关于this指向及其改变指向的问题

2017-12-21 23:56 369 查看
之前被学长问到过关于改变this指向的问题,但是没能完整的回答上来,所以今天就关于这个问题的再看了看

1.关于this指向的问题,我用代码来描述

<input type="button" value="button1">
<input type="button" value="button2">
<script>
//普通函数声明
function a() {
console.log(this);  //window
}
a();
console.log("--------------------------------");

//函数声明赋给变量
var b = function () {
console.log(this);    //window
};
b();
console.log("--------------------------------");

//在构造函数中的this指向
function c() {
this.name = "luoYi";
this.age = 19;
console.log(this);    //window
};
c();
console.log("--------------------------------");

//对象方法调用
var d =  {
run : function (){console.log(this);}    //run
};
d.run();
console.log("--------------------------------");

//事件绑定
var aInput = document.querySelectorAll("input");
aInput[0].onclick = function () {
console.log(this);    //aInput[0]
};
console.log("--------------------------------");

//事件监听
aInput[1].addEventListener("click",function () {
console.log(this);    //aInput[1]
});
console.log("--------------------------------");

</script>


2.关于改变this指向的几种方法

1. call()方法(用作继承时)

function c() {
this.name = "luoYi";
this.age = 19;
console.log(this);    //window
}
function c1() {
c.call(this,age);   ////把this指向c,同时还可以传递参数
//console.log(this);
}
c();
var test = new c1();
c.age = 20;
console.log(test.age);    //19
console.log(test.name);     //luoYi
test.name = "chenHao";
console.log(test.name);     //chenHao


2.apply()方法

console.log(Math.max.apply(null,[1,2,3,4]));    //4


3.bind()方法(es5里面的方法)

它会创建一个函数的实例,其this的值会被绑定到传给bind()函数的值

window.color = "red";
var dn = {
color:"blue"
};
function sayColor() {
console.log(this.color);
}
var objSayColor = new sayColor.bind(dn);
objSayColor();     //blue


4. arguments.callee()

在递归函数中,用
arguments.callee()
改变this的指向,以至于后面调用的时候this的指向不会被改变

function aaa(n){
return n<=2 ? 1 : arguments.callee(n-2)+arguments.callee(n-1);
}
alert(aaa(8));


3.关于call()和apply()方法的概念和区别

区别:

apply()
方法接收两个参数:一个是在其中运行函数的作用域,另一个是参数数组。其中,第二个参数可以是 Array 的实例,也可以是arguments 对象。

call()
方法与 apply() 方法的作用相同,它们的区别仅在于接收参数的方式不同。对于 call()方法而言,第一个参数是 this 值没有变化,变化的是其余参数都直接传递给函数。换句话说,在使用call() 方法时,传递给函数的参数必须逐个列举出来。

call方法:

语法:call(thisObj,Object)

定义:调用一个对象的一个方法,以另一个对象替换当前对象。

说明:call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

apply方法:

语法:apply(thisObj,[argArray])

定义:应用某一对象的一个方法,用另一个对象替换当前对象。

说明:如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。 如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数