【问题标题】:Whats the equivalent of ES6 methods(class) in es5?什么是 es5 中的 ES6 方法(类)的等价物?
【发布时间】:2017-03-19 17:12:17
【问题描述】:

我们如何将 es6 类方法填充到 ES5 中?

我正在看一本书,上面写着:

class Ninja {
    constructor(name) {
        this.name = name;
    }

    swingSword() {
        return true;
    }
}

一样
function Ninja(name) {
    this.name = name;
} 

Ninja.prototype.swingSword = function() {
    return true;
};

我只是问为什么我们在原型上而不是在构造函数中添加 swingSword?

因为函数应该在对象上,而不是在原型链上。

我是对还是错?

【问题讨论】:

  • 你错了,这本书是对的。

标签: javascript ecmascript-6 es6-class


【解决方案1】:

它应该在原型上,方法不是每个实例的数据。想不出有什么语言可以这样实现,类的整个想法是拥有一整类具有相同方法集的对象。

如果将它放在构造函数中,它将是每个使用构造函数创建的实例的唯一函数。例如,每个“方法”有 1000 个对象 == 1000 个函数。

【讨论】:

  • 感谢您的回答。现在我明白了。
  • 实际上,即使您在构造函数中附加函数,也不会每 1000 个实例有 1000 个函数。你最终得到 1000 个闭包和 1 个函数。闭包应该是非常优化的,所以它远没有创建 1000 个不同的函数那么昂贵。此外,对于非常时间关键的方法,它们可能运行得更快(以较慢的对象创建为代价),因为 Javascript 引擎将首先检查 this.func,然后检查 Object.getPrototypeOf(this).func(等等)。但是,是的,原型通常是最好的,而且维护成本更低。
【解决方案2】:

仅将函数添加到对象仅适用于Ninja。要创建扩展Ninja 的类,例如Kunoichi,您通常需要复制Ninja 原型。不幸的是,因为swingSword不在原型中,你的Kunoichi不能挥剑。

您必须在原型中添加该函数才能扩展该类。

【讨论】:

    【解决方案3】:

    var $class = function ($superclass, config) {
        // All classes have a superclass with the root 
        // of this $class hierarchy being Object.
        var self = function (config) {
            // Object.assign or $.extend or ...
            config && Object.assign(this, config);
        };
        self.prototype = new $superclass(config);
        return self;
    };
    
    var A = $class(Object, {
        sayWhat: "Hello, I'm an A",
        say: function () {
            console.log(this.sayWhat);
        }
    });
    
    var B = $class(A, {
        sayWhat: "Hello, I'm a B"
    });
    
    var C = $class(B, {
        say: function () {
            console.log("C SAYS: " + this.sayWhat);
        },
        superSay: function () {
            // how to call a superclass method
            B.prototype.say.call(this);
        }
    });
    
    var a = new A();
    a.say();  // Hello, I'm an A
    
    var b = new B();
    b.say();  // Hello, I'm a B
    
    var c = new C();
    c.say();  // C SAYS: Hello, I'm a B
    
    // create a "one-off" object
    var d = new C({
        sayWhat: "I'm special!",
        say: function () {
            console.log("hey!");
        }
    });
    d.say();  // hey!
    d.superSay();  // I'm special!
    C.prototype.say.call(d);  // C SAYS: I'm special!
    

    【讨论】:

    • 这段代码如何回答这个问题?查看How to Answer 了解如何编写有用的答案。不要只是发布代码转储;您应该包含一些文字来解释您的代码的作用以及它如何回答问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    相关资源
    最近更新 更多