es5 中 ES6 方法(class)的等价物是什么?

Whats the equivalent of ES6 methods(class) in es5?

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

我正在看一本书,上面写着以下内容:

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

    swingSword() {
        return true;
    }
}

相同
function Ninja(name) {
    this.name = name;
} 

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

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

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

我是对还是错?

应该在原型上,方法不是每个实例的数据。想不出有任何语言以这种方式实现它,classes 的整个想法是拥有一整套 class 具有相同方法集的对象。

如果将它放在构造函数中,它将是使用构造函数创建的每个实例的唯一函数。例如,1000 个对象 == 1000 个函数,每个 "method".

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

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


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!