国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > ES6与ES5对比-----'类'

ES6与ES5对比-----'类'

来源:程序员人生   发布时间:2017-03-15 09:45:54 阅读次数:3615次

ES6与ES5对照—–’类’

// ES5

function Application() {
    this.a = 123;
    this.b = 456;

    this.foo = function() {
        return 135;
    }
}

var pro = Application.prototype;

pro.bar = function() {
    return 246;
}

var app = new Application();

console.dir(typeof Application);    // => 'function'
console.dir(Application);           // => [Function: Application]
console.dir(app);                   // => {a:123, b: 456, foo: [function]}
console.dir(typeof app);            // => 'object'
console.dir(app.bar());             // => 246
// ES6

class Application {

    // constructor方法默许返回实例对象,1个类必须有该方法,没有会被默许添加
    constructor() {              
        this.a = 123;           // => this指代新的实例对象,即new的对象
        this.b = 456;
        this.foo = function() {
            return 135;
        }
    }

    bar() {
        return 246;
    }
}

let app = new Application();

console.dir(typeof Application);    // => 'function'
console.dir(Application);           // => [Function: Application]
console.dir(app);                   // => {a:123, b: 456, foo: [function]}
console.dir(typeof app);            // => 'object'
console.dir(app.bar());             // => 246

console.dir(app.constructor);       // => [Function: Application]

* 可以发现,两次的打印1模1样,我们可以理解为class实际上是构造函数的1个语法糖,只是为了让JavaScript看起来更像1门面向对象的语言 *

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生