javascript - Is this a safe way of copying one objects prototype to another? -


say have 1 object prototypal properties have manually set.

an example be

function a() {  };  a.prototype.b = function() {  };  a.prototype.c = function() {  };  a.prototype.d = function() {  }; 

how can extend object a's prototype?

what have tried this;

// obj = extend object // obj2 inherit object  (var prop in obj2.prototype) {             if (obj2.prototype.hasownproperty(prop)) {                 obj.prototype[prop] = obj2.prototype[prop];             }         } 

does using obj2.hasownproperty(prop) ensure properties on a's prototype have copied?

is there better way of doing this?

generally, it's not advisable try , emulate patterns other languages javascript. javascript uses prototypal inheritance, , not standard oo inheritance (such in java). yes, can copy methods 1 prototype another, not advisable, because you're blowing encapsulation of inner object out of water. if want copy methods, can setting 1 objects prototype equal other.

here 1 pattern doing inheritance

// object want inherit function bar() {} bar.prototype.original = function() {}  // object inherit bar function foo() {} // first map prototypes foo.prototype = new bar();  // add additional methods foo foo.prototype.somethingelse = function() {} 

instead of doing new bar() object.create(bar), of commenters have pointed out, not supported in ie8 , below. functional difference between 2 new bar() execute constructor of bar, while latter not, may or may not matter you. object.create() technically more correct way go, can deal breaker unless willing lose ie8 or use shim.

here pattern, preferred, using composition instead

// object want inherit function bar() {} bar.prototype.original = function() {}  function foo() {     this.bar = new bar(); } foo.prototype.somethingelse = function() {     // foo has bar, isn't bar     this.bar.original(); } 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -