鍍金池/ 問(wèn)答/HTML/ ES6 用class關(guān)鍵之創(chuàng)建的類 必須new才能訪問(wèn)、怎么破?

ES6 用class關(guān)鍵之創(chuàng)建的類 必須new才能訪問(wèn)、怎么破?

示例:

class Demo
{
    // 構(gòu)造方法
    constructor(param){}
    // 靜態(tài)方法
    static hello()
    {
        return "hello";
    }
    // 實(shí)例方法
    world()
    {
        return "world";
    }
}

// 正常
console.log(Demo.hello());

// 報(bào)錯(cuò)
Demo();

以問(wèn):

我現(xiàn)在有個(gè)需求是無(wú)New實(shí)現(xiàn)靜態(tài)方法可讀,并且加括號(hào)就自動(dòng)返回一個(gè)Demo的實(shí)例,但現(xiàn)在class創(chuàng)建的類必須用New才能訪問(wèn),是否意味著無(wú)New構(gòu)建這套方案無(wú)法實(shí)現(xiàn)?

回答
編輯回答
巷尾

圖片描述

你看es6 的說(shuō)明 文檔, class 是不能當(dāng)函數(shù)運(yùn)行的。

2017年8月9日 07:55
編輯回答
忘了我

class 肯定不行的,用es5寫法吧

function Demo()
{  
    if(!(this instanceof Demo)){
        return new Demo();
    }
    return this;
}
Demo.prototype.world = function(){return 'world'}
Demo.hello = function(){return 'hello'} 
console.log(Demo.hello()); 
Demo();
2017年9月1日 07:18
編輯回答
別硬撐

使用es5的function啊

2017年2月8日 13:34
編輯回答
忘了我

我想你需要的是這個(gè)
https://github.com/CGamesPlay...

2018年9月7日 06:49
編輯回答
筱饞貓

這是規(guī)定 es6 的class 可以看做是一個(gè)語(yǔ)法糖。規(guī)定調(diào)用class 必須要使用new關(guān)鍵字。如果樓主不想用new 只能更換方法。

2017年9月1日 18:38