0

how might we can write in Java script as I'm new in the world of Java script.

 function Car() {
     this.type = "Car";
   };

function Ferrari() {
     this.name = "Ferrari";
   };

Ferrari.extends(Car);
   var f = new Ferrari();
   f.name // Ferrari
   f.type // Car

None of the answer help me as i'm following eloquentjavascript book

Tyshawn
  • 39
  • 4
  • See this answer: http://stackoverflow.com/a/10430875/921204 - Also make sure to read the comments. – techfoobar Apr 28 '15 at 10:47
  • While the duplicate isn't an exact match for the question, the accepted answer covers it (and lots of other stuff besides). There are also many other resources on the internet for how to extend javascript "classes". Once you've done some research on those and come up with a preferred solution, feel free to ask questions about that too. :-) – RobG Apr 28 '15 at 10:57

1 Answers1

0

Javascipt is a hybrid language with prototypical approach. To "extend" in js context is to inherit by the prototype. Some modern browser supports Object.create() which internally iterates through each prototype property and copy across.

This snippet is from MDN:

Examples
Example: Classical inheritance with Object.create()

Below is an example of how to use Object.create() to achieve classical inheritance. This is for single inheritance, which is all that JavaScript supports.

// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle? ' + (rect instanceof Rectangle)); // true
console.log('Is rect an instance of Shape? ' + (rect instanceof Shape)); // true
rect.move(1, 1); // Outputs, 'Shape moved.'

Hope this helps.

daxeh
  • 1,083
  • 8
  • 12
  • 1
    so how we can write own extend methods – Tyshawn Apr 28 '15 at 11:10
  • yes, but via the object's prototype. example above "subclass extends superclass". but do check out the link that the moderator has provided to a similar topic with answers. good luck and have fun prototyping! – daxeh Apr 28 '15 at 11:21