颠覆你的Python实践

javascript面向对象编程之this介绍

2017-10-20  本文已影响32人  亭子青年

介绍

依旧是那个不会的带娃的测试。

简介

作为测试,了解一点js还是非常有必要的

今天介绍的是关于js(前端语言)中this的使用(区别于服务端语言中的this)

js是一种面向对象的语言,但是却没有class的说法

定义一个类

在js中,定义类,其实就是定义一个方法,如果这个方法中一般都会使用this关键字。

// 定义一个名叫person的类
var person = function (name, age) {
    this.name = name;
    this.age = age;
    this.sayHello = function () {
        var str = this.name + "love you"
        return str;
    }
}
// 创建一个名叫tingzi的对象
me = new person("tingzi", 124);
// me.name
// me.age
// me.sayHello()

this说明

情况1:this就表示实例对象

// 定义一个名叫person的类
var person = function (name, age) {
    this.name = name;
    this.age = age;
    this.sayHello = function () {
        var str = this.name + "love you"
        return str;
    }
}
// 创建一个名叫tingzi的对象
me = new person("tingzi", 124);
// me.name
// me.age
// me.sayHello()

情况2:this代表的是事件触发对象

// 这里的this表示的是id为btn01的这个对象
document.getElementById("btn01").click(function () {
    var cssrule = this.CSSPageRule;
})

情况3:情况1+情况2的混合

var person = function (name, age) {
// function里面的第一层this都表示的是实例对象
    this.name = name;
    this.age = age;
    this.sayHello = function () {
// 这里的this代表的是person的实例对象
        var str = this.name + "love you"
        return str;
    }
    this.btn01_click = function () {
        document.getElementById("btn01").click(function () {
// 这里的this代表的是id为btn01的这个对象
            return this.CSSPageRule;
        })
    }
}

情况4:更复杂的情况

var person = function (name, age) {
    this.name = name;
    this.age = age;
    this.sayHello = function () {
        var str = this.name + "love you"
        return str;
    }
    this.btn01_click = function () {
        document.getElementById("btn01").click(function () {
            return this.CSSPageRule;
            //这里是我需要重点说明的地方
            this.sayHello();
        });
    }
}

me = new person("heting", 124);

我们在onclick中调用了这个类的sayHello()方法,而sayHello方法中使用了this,name这里的this代表的是person的实例对象还是id为btn01的这个元素呢?
答案:id为btn01的那个元素

华丽丽的总结

根据上面的总结,我修改一下我们的代码

var person = function (name, age) {
    // 修改1
    var me = this;  // 注意,var开头的是私有的,实例也不能访问的对象
    this.name = name;
    this.age = age;
    this.sayHello = function () {
        // 修改2
        var str = me.name + "love you"
        return str;
    }
    this.btn01_click = function () {
        document.getElementById("btn01").click(function () {
            return this.CSSPageRule;
        });
        this.sayHello();
    }
}

me = new person("heting", 124);

上一篇 下一篇

猜你喜欢

热点阅读