<script> function inherit_A(Child, Parent) { var F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.super = Parent.prototype; } function Par(name) { this.name = name || 'kill' } Par.prototype.say = function () { return this.name } function Chi() {} inherit_A(Chi, Par) obj = new Chi() alert(obj.say()) //underfined </script> 
  • This pattern is of interest when inherited from the prototype - zloctb
  • On CoffeeScript look, in between times. It helps not to write an extra boilerplate. - drdaeman

1 answer 1

 function inherit_A(Child, Parent) { var F = function () { }; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.prototype.super = Parent.prototype; // parent prototype better store in child prototype Child.prototype.$super = function() { // method to call parent constructor Parent.apply(this, arguments); } } function Par(name){ this.name=name||'kill' } Par.prototype.say = function() { return this.name; } function Chi( name ){ this.$super( name ); // or this.$super.apply(this, arguments); // apply all arguments to parent constructor } inherit_A(Chi, Par); var c1 = new Chi(); var c2 = new Chi('test'); console.log( c1.say() ); // -> kill console.log( c2.say() ); // -> test 

Javascript apply

  • Do these lines copy properties? Without them, will only properties in prototypes be inherited? this. $ super (name); // or this. $ super.apply (this, arguments); - zloctb
  • Firstly, there are 2 different options. Both just call the parent constructor, so they don’t copy anything, copy inherit_A In general, you would like to learn some mat part ... - Zowie
  • Why did you make a conclusion about the level of my knowledge in mathematics? - zloctb
  • LOL, Teach materiel - Zowie