在 javascript 中创建类时,您可以通过访问函数的prototype.
function Foo() {
}
Foo.prototype.get = function() {
return this._value;
}
Foo.prototype._value = 'foo value';
var foo = new Foo();
console.log(foo.get()); // logs "foo value"
Run Code Online (Sandbox Code Playgroud)
如何使用 ecmascript 6 达到类似的效果class?
// this doesn't work
class Bar {
get() {
return this._value;
}
// how to declare following default value properly?
_value: "bar value"
}
var bar = new Bar();
console.log(bar.get()); // logs undefined
Run Code Online (Sandbox Code Playgroud)