好吧,我来尝试回答一下这个问题。
ECMAScript 6 类作为语法糖的背景
ES6 类只是 ECMAScript(又名 JavaScript)中普通原型继承的语法糖。
class Foo {
constructor(a, b) {
this.c = a;
this.d = b;
}
static bar() {}
another() {}
}
这相当于:
function Foo(a, b) {
this.c = a;
this.d = b;
}
Foo.bar = function() {};
Foo.prototype = {
another: function() {}
};
不过,在 ES6 中进行继承比旧方法要容易得多:
class Foo extends Bar {
...
}
在 ES5 或更早版本中做同样的事情很容易出现问题,但这有点偏离主题。
问题
状态由实例承载 - 在此上下文中状态意味着什么以及示例(首选 c++)
类的实例是类似于 C++ 的对象。
class Foo {
constructor(a) {
this.value = a;
}
getValue() {
return this.value;
}
}
var foo = new Foo(42);
console.log(foo.getValue()); // prints 42
等价于 C++:
class Foo {
private:
int value;
public:
Foo(int a) : value(a) {}
int getValue() {
return value;
}
};
void main() {
Foo foo = new Foo(42);
std::cout << +foo.getValue() << std::endl;
}
如您所见,实例类的行为在 ES6 和 C++ 中是相同的,但是没有字面上的等价物private
or public
ES6 中的封装。
方法由类携带 - 这可能意味着,如果我想知道对象的方法,我需要查看该对象的类。
在 ECMAScript 中,您可以重写类实例上的函数,因为它就像其他所有东西一样只是一个对象。
var foo = new Foo(42);
foo.getValue = function() { return this.value + 1; };
console.log(foo.getValue()); // returns 43
console.log(foo.constructor.prototype.getValue.call(foo)); // returns 42
Using .constructor.prototype
当对象被实例化时,对象的原型得到该对象的原型new
关键词。
继承仅是结构和行为——仅继承结构和行为?
他们选择的措辞很麻烦。我相信他们的意思是,就像在 ECMAScript 中一样,类的实例就像其他任何对象一样,您可以修改几乎所有内容,而在 C++ 中,类的实例有更严格的要求。您不能向实例添加新方法,不能添加新属性,也不能打破语言为您提供的约束。
我希望这回答了你的问题。如果有什么不清楚的地方,请评论,我会编辑。