Reputation: 100020
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?
Upvotes: 0
Views: 101
Reputation: 166
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.
Upvotes: 2
Reputation: 1442
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();
Upvotes: 1
Reputation: 85545
You may use Object.create():
var foo = {
field1: '',
method1: function(){}
};
var bar = Object.create(foo);
Upvotes: 1