0

I'm trying to copy Object class and then modify prototype of the new copied class. However, changes to new class prototype gets reflected to original Object class. Example:

var MyClass = Object;
MyClass.prototype.doSomething = function() {...};

Object.prototype.doSomething(); //it gets reflected to original object

Is there some way to copy a class without that annoying reflection (I know that sometimes it is a good thing, but right now, I just need to get rid of it)?

onlyMe
  • 127
  • 9
  • MyClass = function(){}. Would already inherit from Object. http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR May 05 '14 at 15:37

3 Answers3

0

I would just use prototypical inheritance instead of worrying about "cloning" in this case. There are several JS libraries that can help with that.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

Yes, you should create a new Object and use it for your prototype:

function MyClass(){}
MyClass.prototype = new Object;
MyClass.prototype.doSomething = function() { ... };

In modern engines you should use Object.create for this:

function MyClass(){}
MyClass.prototype = Object.create(Object.prototype);
MyClass.prototype.doSomething = function() { ... };
Paul
  • 139,544
  • 27
  • 275
  • 264
0

Actually, there is no way to copy a function reliably in Javascript. Provided that Object is another function you can do the following trick. Let's first rename it to Base not to shadow build-in Object function.

function MyClass(){
   Base.apply(this, arguments); //call Base on a newly created object.
   //the rest of configuration goes here.
};

MyClass.prototype = Object.create(Base.prototype); //"copy" Base.prototype. Notice Object is built-in function.

MyClass.prototype.constructor = MyClass; //We want instanceof to work...

MyClass.prototype.doSomething = function(){}; //Add new method.

Base.prototype.doSomething !== MyClass.prototype.doSomething; //true
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98