oop - JavaScript Functional Classes -
i learning object oriented programming in javascript udacity course. know among below best technique create functional object , why.
first code:
var car = function(loc){ var obj = {loc:loc}; extend(obj, car.methods); return obj; } car.methods = { move: function(){ this.loc++; } };
second code:
isnt above code same as:
var car = function(loc){ var obj = {loc:loc}; obj.move= function(){ this.loc++; } return obj; }
third code
var car = function(loc){ var obj = {loc:loc}; obj.move=move; return obj; } move=function(){ this.loc++; };
i want know, style of coding 1 should follow. understand third code better second because more instances of functions created whenever use car function. doesn't first code create more instance of same function?
thanks in advance.
answer: none of above. try this:
function car(loc) { this.loc = loc; } car.prototype.move = function () { this.loc++; }; var obj = new car(someloc); obj.move();
this uses object prototyping javascript's implementation of object-oriented programming. can read more prototypes , inheritance here on mdn.
the reason why preferred method because organizes code lot better, , object can identified car
using instanceof
. i'll extend example below demonstrate properties of inheritance:
// vehicle constructor function vehicle(wheels, speed, loc) { this.wheels = wheels; this.speed = speed; this.loc = loc; } // instance method move vehicle.prototype.move = function () { this.loc += this.speed; }; // car constructor function car(loc) { // js equivalent of super() vehicle.call(this, 4, 60, loc); } // override instance method move car.prototype.move = function () { this.loc++; }; // make car inherit vehicle car.prototype.__proto__ = vehicle.prototype; // construct instance of car loc of 0 var obj = new car(0); // obj instance of vehicle... if (obj instanceof vehicle) { console.log('wheels: %d', obj.wheels); // 4 console.log('speed: %d', obj.speed); // 60 console.log('loc: %d', obj.loc); // 0 } // ...and instance of car if (obj instanceof car) { obj.move(); console.log('loc: %d', obj.loc); // 1, not 60 }
this demonstrates how can use prototype chain override instance methods, , how inheritance allows obj
instance of both car
, vehicle
. hope can see why using prototype chain preferred method.
Comments
Post a Comment