Typescript generates javascript code for simple class inheritance -


i have question how typescript generates javascript code simple class inheritance. below typescript code followed generated javascript code.

typescript code:

class animal {     constructor(public name: string) { }     move(meters: number) {         alert(this.name + " moved " + meters + "m.");     } }  class cat extends animal {     constructor(name: string) { super(name); }     move() {         alert("run...");         super.move(5);     } } 

generated javascript code:

var __extends = this.__extends || function (d, b) {     (var p in b) if (b.hasownproperty(p)) d[p] = b[p];     function __() { this.constructor = d; }     __.prototype = b.prototype;     d.prototype = new __(); }; var animal = (function () {     function animal(name) {         this.name = name;     }     animal.prototype.move = function (meters) {         alert(this.name + " moved " + meters + "m.");     };     return animal; })();  var cat = (function (_super) {     __extends(cat, _super);     function cat(name) {         _super.call(this, name);     }     cat.prototype.move = function () {         alert("run...");         _super.prototype.move.call(this, 5);     };     return cat; })(animal); 

you see generated javascript code contains __extends(d, b). function copies base class properties derived class: d[p] = b[p];.

my question why copying required, setting cat.prototype = _super; had been fine , inline javascript prototype based inheritance. copying the base ctor properties derived ctor d[p] = b[p]; seems wastage of memory.

static properties/functions not exist on prototype. prototype used when new instance created.

so, first loop copies static properties (which include functions). not copying on prototype (as for(var v in p) not include prototype or properties/functions declared on prototype).

the best way preserve prototype chain in javascript set prototype of subclass instance of super class. in case above, means equivalent of this:

cat.prototype = new animal(); 

that way, when javascript looking matching property, follow prototype chain through inheritance hierarchy.

if set directly:

cat.prototype = animal.prototype 

that mean runtime changes cat prototype affect animal point same instance (which not desirable).


Comments

Popular posts from this blog

Change the color of an oval at click in Java AWT -

c# - Unity IoC Lifetime per HttpRequest for UserStore -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -