Javascript 笔记与总结(1-4)this

js 中函数的 4 种调用方式:

① 作为普通函数来调用,this 的值指向 window,准确地说,this 为 null,被解释成为 window。在 ECMAScript5 标准中,如果 this 为 null,则解释成 undefined

<script>
function t(){
    this.x = 'hello';
}
t();
alert(window.x);
</script>

弹出:hello

 

② a.作为对象的方法来调用,this 指向方法的调用者,即该对象

<script>
var obj = {x:'hello',y:'world',t:function(){alert(this.x)}};
obj.t();
</script>

弹出:hello

 

b.

<script>
var obj = {x:'hello',y:'world',t:function(){alert(this.x)}};

var dog = {x:'wang'};
dog.t = obj.t;
dog.t();
</script>

弹出:wang

作为方法调用时,this 指向其调用那一刻的调用者,即母体对象,不管被调用函数,声明时属于方法还是函数

 

c.

<script>
var obj = {x:'hello',y:'world',t:function(){alert(this.x)}};

var dog = {x:'wang'};
dog.t = obj.t;
dog.t();

show = function(){
    alert('show '+this.x);
}
dog.t = show;
dog.t();
</script>

 

d.

<script>
var obj = {x:'hello',y:'world',t:function(){alert(this.x)}};

var dog = {x:'wang'};
dog.t = obj.t;
dog.t();

show = function(){
    alert('show '+this.x);
}
dog.t = show;
dog.t();
</script>

弹出:show wang

 

③ 作为构造函数调用时

js 中没有类的概念,创建对象使用构造函数来完成,或者直接用 json 格式{} 来写对象

<script>
function Dog(name,age){
    this.name = name;
    this.age = age;
    this.bark = function(){
        alert(this.name);
    }
}
var dog = new Dog('妞妞',2);
dog.bark();
</script>

弹出:妞妞

new Dog 发生了一下几个步骤:

a. 系统创建空对象{},(空对象 construct 属性指向 Dog 函数)

b. 把函数的 this 指向该空对象

c. 执行该函数

d. 返回该对象

 

例:

<script>
function Robit(){
    this.name = '瓦力';
    return 'wali';
}
var robit = new Robit();
console.log(robit);
</script>

这段代码将输出?

答案:

 Robit {name: "瓦力"}

输出的是 Robit 对象,因为函数作为构造函数运行时,return 的值是忽略的,依然返回对象(return 无意义)。

 

 

④ 函数通过 call,apply 调用

语法格式:函数.call(对象,参数1,参数2...参数n);

<script>
function t(num){
    alert('我的年龄是 '+this.age);
    alert('虽然我看起来像 '+(this.age+num));
}
var human = {name:'迭戈.科斯塔',age:27};
human.t = t;
human.t(10);
</script>

弹出:我的年龄是 27

弹出:虽然我看起来像 28

 

接下来,不把 t 赋为 human 的属性,也能把 this 指向 human

<script>
function t(num){
    alert('我的年龄是 '+this.age);
    alert('虽然我看起来像 '+(this.age+num));
}

var giroud = {name:'Giroud',age:28};
t.call(giroud,-5);
</script>

弹出:我的年龄是 28

弹出:虽然我看起来像 23

【分析】:

fn.call(对象,参数1,参数2...参数n);

运行如下:

a. fn 函数中的 this 指向对象 obj

b. 运行 fn(参数1,参数2...参数n)

 

posted @ 2015-04-15 23:27  nemo20  阅读(190)  评论(0编辑  收藏  举报
访客数:AmazingCounters.com
2016/05/17 起统计