Appendix A: ES6 class - hochan222/Everything-in-JavaScript GitHub Wiki
class C {
constructor() {
this.num = Math.random();
}
rand() {
console.log( "Random: " + this.num );
}
}
var c1 = new C();
c1.rand(); // "Random: 0.4324299..."
C.prototype.rand = function() {
console.log( "Random: " + Math.round( this.num * 1000 ));
};
var c2 = new C();
c2.rand(); // "Random: 867"
c1.rand(); // "Random: 432" -- oops!!!
class C {
constructor() {
// make sure to modify the shared state,
// not set a shadowed property on the
// instances!
C.prototype.count++;
// here, `this.count` works as expected
// via delegation
console.log( "Hello: " + this.count );
}
}
// add a property for shared state directly to
// prototype object
C.prototype.count = 0;
var c1 = new C();
// Hello: 1
var c2 = new C();
// Hello: 2
c1.count === 2; // true
c1.count === c2.count; // true
accidental shadowing
class C {
constructor(id) {
// oops, gotcha, we're shadowing `id()` method
// with a property value on the instance
this.id = id;
}
id() {
console.log( "Id: " + this.id );
}
}
var c1 = new C( "c1" );
c1.id(); // TypeError -- `c1.id` is now the string "c1"
super๋ ์ ์ ์ผ๋ก ๋ฐ์ธ๋ฉ ๋๋ค.
class P {
foo() { console.log( "P.foo" ); }
}
class C extends P {
foo() {
super();
}
}
var c1 = new C();
c1.foo(); // "P.foo"
var D = {
foo: function() { console.log( "D.foo" ); }
};
var E = {
foo: C.prototype.foo
};
// Link E to D for delegation
Object.setPrototypeOf( E, D );
E.foo(); // "P.foo"
toMethod
var D = {
foo: function() { console.log( "D.foo" ); }
};
// Link E to D for delegation
var E = Object.create( D );
// manually bind `foo`s `[HomeObject](/hochan222/Everything-in-JavaScript/wiki/HomeObject)` as
// `E`, and `E.[Prototype](/hochan222/Everything-in-JavaScript/wiki/Prototype)` is `D`, so thus
// `super()` is `D.foo()`
E.foo = C.prototype.foo.toMethod( E, "foo" );
E.foo(); // "D.foo"