您的位置:首页 > Web前端 > JavaScript

js中this指向问题

2013-08-20 17:42 896 查看
1.在全局范围内使用this的时候 它指向的是全局对象

this
Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}


2.方法调用模式

test.foo();   //这里调用会吧 this指向test对象


3.函数调用

alert();  //这里的this是 全局

//这里有些问题  一些对象内部的方法 直接调用会默认是全局对象上 。
//使用 var _this=this 可以解决这个问题


4.构造器模式调用

var Gzq = function(name){
this.name=name;
}
var oNewGzq=new Gzq('haha'); //new以后  把this给了新的对象 oNewGzq


5.apply/call 显示设置模式

var  arrtest=[3,4];
var sum=add.apply(null,arrtest);//用apply将值 传递给了 add方法
console.log(sum);

var applytest={
name:"apply test"
}

//将genName 这个方法 给予了 applytest 。
var applyTestValue= Gzq.prototype.getName.apply(applytest);

console.log(applyTestValue);



当使用 Function.prototype 上的 call 或者 apply 方法时,函数内的 this 将会被 显式设置为函数调用的第一个参数。

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