views:

89

answers:

4

Hi,

How do I inherit with the Object.create()? I tried these, but none are working:

var B = function() {};
var A = function() {};
A = Object.create(B);
A.prototype.C = function() {};

and

var B = function() {};
var A = function() {};
A.prototype.C = function() {};
A = Object.create(B);

and

var B = function() {};
A = Object.create(B);
var A = function() {};
A.prototype.C = function() {};

Nothing worked. How am I supposed to use this new Object.create()-function?

A: 

The original documentation for Douglas' Object.create is here http://javascript.crockford.com/prototypal.html . Make sure you have included the definition of the the method

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
Steve
A: 

You can define Object.create yourself, but if it is not native you will have to deal with it being enumerated in every for in loop you use for objects.

So far only new webkits- Safari5 and Chrome natively support it.

kennebec
+3  A: 

Object.create() is used to inherit objects, not constructors like you're trying to do. It pretty much creates a new object with the old object set as its prototypal parent.

var A = function() { };
A.prototype.x = 10;
A.prototype.say = function() { alert(this.x) };

var a = new A();
a.say(); //alerts 10

var b = Object.create(a);
b.say(); //alerts 10
b.x = 'hello';
b.say(); //alerts 'hello'

And just to make sure b is not just a clone of a,

a.x = 'goodbye';
delete b.x;
b.say(); //alerts 'goodbye'
Chetan Sastry
Damn, then it does not fit my situation. I need to define a "class" that extends another "class".
rFactor
A: 

You can find useful information about JavaScript inheritance on Mozilla Development Center.

el.pescado