0

In JavaScript, if I initialize an object like so:

var foo = {};

is there a way to get the prototype of that object? The prototype quite well may be undefined. But actually, what I really want is just the defined fields and functions/methods that foo may have:

var foo = {

field1: '',
method1: function(){}

};

I am trying to create a classical inheritance system, but Object.create() seems to want arguments that represent prototypes and nothing else.

In other words, I want var bar = {} to inherit from foo. But both bar and foo are objects initialized with {}.

How can I add the methods from one object to another with or without dealing with prototypes?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 1
    If you already have two built objects, you can just copy the properties of one object over to the other. – jfriend00 Feb 16 '15 at 06:16
  • Objects have instance specific members that can be set with a factory or constructor function and a prototype chain that can be used to specify shared members; usually behavior (functions) and immutable default values (primitive types like string and number). Using Object create to inherit both instance specific members and shared members could result in some unexpected behavior (because it shows a misunderstanding what prototype is) maybe the following can help you: http://stackoverflow.com/a/16063711/1641941 – HMR Feb 16 '15 at 15:34

3 Answers3

2

When you instantiate an object with new ({} is the same as new Object()), the prototype becomes its properties. Here is a simple example of prototypal inheritance :

// Foo constructor
var Foo = function() {};
Foo.prototype = {
    field1: '',
    method1: function(){}
};

// bar constructor
var Bar = function(){
    Foo.call(this); // calling the parent ctor
};
Bar.prototype = Object.create(Foo.prototype); // inherit from Foo
Bar.prototype.constructor = Bar; // set the ctor just in case it was set by Foo

var bar_instance = new Bar();
bar_instance.method1(); // <-- it works!

I would suggest you go read the code for Google's Closure Library, PrototypeJS and Mootools Class system to inspire you in your endeavor.

Hope this helps.

G Roy
  • 166
  • 3
1

You may use Object.create():

var foo = {
   field1: '',
   method1: function(){}
};
var bar = Object.create(foo);
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
1

You may try this:

http://jsfiddle.net/kc0Lshrp/1/

var foo = {};
foo.constructor.prototype.field1='FOO';
foo.constructor.prototype.method1=function(){ alert(this.field1)};
var bar={field1:'BAR'};
bar.prototype=Object.create(foo);
bar.method1();
Rakesh_Kumar
  • 1,442
  • 1
  • 14
  • 30
  • 1
    Isn't foo.constructor.prototype Object.prototype? Maybe not a good idea to change that: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#Bad_practice.3A_Extension_of_native_prototypes – HMR Feb 16 '15 at 15:29