关于this,关于你

2016-12-20  本文已影响0人  旧丶时候
0.前言
最近北京雾霾挺严重的,希望程序员们注意身体啊!!!好了进入正题吧,我们在敲代码中,常常会用到this,那么问题就来了,有时候你想的this应该指的是什么,但往往有的时候会和你想的不一样,那么我们接下来就来看一下在不同的地方使用this代表的是什么意思.....
1.this定义

this 定义:this是包含它的函数作为方法被调用时所属的对象

2.this的使用地方

1 普通场景下的函数this代表window
2 构造函数中this代表新对象
3 对象内部的函数属性,函数内this表示当前对象
4 事件处理函数,this表示当前dom对象
5 call()与apply() this表示第一个参数

3.代码实现
3. 1.1普通函数

在普通函数中this代表的是window。

//1.普通函数
    function f1(){
        console.log(this);//输出window
    }
    f1(); ```
3.1.2字面量方式创建一个匿名函数

在这个用字面量方式创建一个匿名函数中this也代表了window。

//2.字面量方式创建一个匿名函数
    var f2 = function(){
        console.log(this);//输出window
    };
    f2();
3.2构造函数中的this代表新对象

Duang~~在构造函数中this代表了Liu实例出来新的对象p。

//构造函数中this代表新对象
    function Liu(age,color,making){
        this.age = age;
        this.color = color;
        this.making = making;
            console.log(this);//输出Liu {age: 18, color: "yellow", making: "wood"}
    }
    var p = new Liu(18,"yellow","wood");
    console.log(p);//输出Liu {age: 18, color: "yellow", making: "wood"} 
3.3对象内部的函数属性,函数内this表示当前对象
//3对象内部的函数属性,函数内this表示当前对象
    var person={
        name:"Mr_Liu",
        age:16,
        say:function(){
                console.log("我叫"+this.name);
                console.log(this);//输出 Object {name: "Mr_Liu", age: 16}
        }
    }
    person.say();
3.4事件处理函数,this表示当前DOM对象
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>关于this,关于你</title>
</head>
<body>
    <input type="button" id="btn1" value="按钮">
    <script type="text/javascript">
        //4 事件处理函数,this表示当前dom对象
        document.getElementById("btn1").onclick = function(){
        console.log(this);//输出 <input type="button" id="btn1" value="按钮">
     }
    </script>
</body>
</html>

在事件处理函数中,首先,咱们得获取到按钮这个节点,然后给按钮添加一个点击事件,当我们点击按钮的时候,事件处理函数中this代表的是DOM对象 <input type="button" id="btn1" value="按钮"> 这个标签。

3.5 call() 与apply() 中的this代表第一个参数
var per1 = {
            name:"二雷",
            say: function(p1, p2){
                console.log("Hi, " + p1 + " and " + p2 + ", My name is " + this.name);
            },
        };
    per1.say("lilei", "hanmeimei");
    var per3 = {
        name: "三雷",
    };
per1.say.call(per3, "lilei", "hanmeimei");//输出 Hi, lilei and hanmeimei, My name is 三雷
per1.say.apply(per3, ["lilei","hanmeimei"]);//输出 Hi, lilei and hanmeimei, My name is 三雷

每个函数都有call()apply() 方法:

1、他们可以出触发函数,并设置参数
2、让一个对象去借用另一个对象的方法,让另一个对象的方法为己所用

在上面咱们可以看出要想让per3借用per1里面的方法为自己作用,我们就想起来用call()apply()的方法,当我们per1调用say() 方法的时候this.name打印出来的是二雷,而当 per3call()apply()借用per1里面的say() 方法的时候,this.name打印出来就是咱们调用call()和apply()里面传入的第一个参数per3里面的三雷,那么结果就出来了,call() 与apply() 中的this代表第一个参数

apply与原理与call相似,不同之处在于给函数传递的参数的方式不一样。

4.后记

本文到这里也就结束了,最后我希望我写的文章对你有所帮助,如果你喜欢就带走吧!!!点赞,分享。

上一篇 下一篇

猜你喜欢

热点阅读