javascript之this详解
2014-07-01 01:29
441 查看
javascript的this不同于java、php等的this,javascript的this灵活多变比较复杂,下面就一一介绍不同情况下的this。
1.函数作为普通函数调用时,this指向window,准确的说this为null,但被解释成window。下面看一个例子
2.函数作为对象的方法来调用时,this指向方法的调用者,即母体对象,不管被调用函数声明时属于谁。下面看一个例子证明这一点。
3.函数作为构造函数调用时,请看下面分析的例子
4.函数通过call、apply调用其中this也要发生变化。
call函数语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]]) arg1...argN可以是任意类型。
apply函数语法:apply([thisObj[,argArray]])
第二个参数是一个数组。
call和apply用法和意义一样,下面对call进行解释:
fn.call(对象obj,参数1,参数2...参数n)
运行如下:
a).fn函数中的this指向对象obj
b).运行fn(参数1,参数2...参数n);
具体例子:
下面看几个例子巩固一下:
请思考一个问题:有this操作的,(如this.age = XX)的函数不能直接调用而是要new来调用?这个说法是对的,因为直接调用的this指向window,将会污染全局变量。
1.函数作为普通函数调用时,this指向window,准确的说this为null,但被解释成window。下面看一个例子
console.log(window.xx);//undefined function t(){ this.xx = 'jhon'; } t(); console.log(window.xx);//jhon
2.函数作为对象的方法来调用时,this指向方法的调用者,即母体对象,不管被调用函数声明时属于谁。下面看一个例子证明这一点。
var obj = {name:'name',age:2,t:function(){console.log(this.name)}}; var dog = {name:'wangcai'}; dog.t = obj.t; dog.t(); /*结果打印的是wangcai*/
3.函数作为构造函数调用时,请看下面分析的例子
function Dog(name,age){ this.name = name; this.age = age; this.bark = function(){ console.log("i am " + this.name); } } var dog = new Dog('huzi',2); dog.bark(); /* 结果为:i am huzi 结果分析 new Dog发生了以下几个步骤: a.系统创建空对象{}(空对象constructor属性指向Dog函数) b.把函数的this指向空对象 c.执行该函数 d.返回该对象 */
function Dog(name,age){ this.name = name; this.age = age; this.bark = function(){ } return 'abc'; } var dog = new Dog('huzi',2); console.log(dog); /* 上面的dog是什么呢? 经过打印可以知道dog仍热是一个对象,而不是'abc'.因此在构造函数中return的值是忽略的,还是返回对象。 */
4.函数通过call、apply调用其中this也要发生变化。
call函数语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]]) arg1...argN可以是任意类型。
apply函数语法:apply([thisObj[,argArray]])
第二个参数是一个数组。
call和apply用法和意义一样,下面对call进行解释:
fn.call(对象obj,参数1,参数2...参数n)
运行如下:
a).fn函数中的this指向对象obj
b).运行fn(参数1,参数2...参数n);
具体例子:
function Animal(){ this.name = 'Animal'; this.showName = function(){ console.log(this.name); } } function Dog(){ this.name = 'dog'; } var animal = new Animal(); var dog = new Dog(); animal.showName.call(dog); /* 结果:dog * /
下面看几个例子巩固一下:
xx = "this is window"; var dog = {xx:'dog',showName:function(){console.log(this.xx);}}; var temp = dog.showName; temp(); /*结果:this is window*/
xx = "this is window"; var dog = {xx:'dog',showName:function(){console.log(this.xx);}}; var cat = {xx:'cat'}; (cat.showName = dog.showName)(); /*结果:this is window */
请思考一个问题:有this操作的,(如this.age = XX)的函数不能直接调用而是要new来调用?这个说法是对的,因为直接调用的this指向window,将会污染全局变量。
相关文章推荐
- javascript this详解
- JavaScript中的this用法详解(续)
- 详解 JavaScript 中的 this
- 详解 JavaScript 中的 this
- 详解 JavaScript 中的 this
- javascript this详解(转)
- 详解 JavaScript 中的 this
- 详解JavaScript中的this
- 详解Javascript 中的this指针
- 详解 JavaScript 中的 this
- javascript this详解(转)
- 详解Javascript. 中的this指针
- Javascript的关键字this详解
- 详解JavaScript中的this
- javascript this 详解
- javascript this详解
- javascript this详解(转)
- javascript this 详解
- JavaScript 之 this 详解
- 详解JavaScript中的this