Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prototype chain in javascript

Suppose I have two constructor function:

var Person = function(xx,xx,xxx,xxxxxxx) {
  //Person initialization
}

var Man = function(xx,xx,xxx,xxx) {
  //Man initialization
}

And I want Man extends from Person.

The following is what I thought:

Given a created Man object:

var m=new Man("xx",....);

1) when a property of m is accessed,it will search it in Man.prototype.

2) If not find, It should find it in Man.prototype.__prop__.

So what I have do is make the Man.prototype.__prop__ linked to Person.prototype.

I know this is the common way:

function inherit(superClass) {
    function F() {}
    F.prototype = superClass.prototype;
    return new F;
}
Man.prototype=inherit(Person);

But when I try this:

Man.prototype.prototype=Person.prototype.

Why it does not work?

like image 916
hguser Avatar asked Jan 17 '23 05:01

hguser


1 Answers

It sounds like you actually want to link instances of Man to an instance of Person that retains any properties added in its constructor, in which case you might really want something like this:

function Person(a, b) {
    this.a = a;
    this.b = b;
}

function Man() {}
Man.prototype = new Person("val1", "val2");

var m = new Man();
console.log(m.a);

...which prints val1.

Additional Ramblings

The purpose of inherit is to create an object from a function whose prototype is that of the given super class (without explicitly using new), which is exactly what it does. Therefore, the following prints string:

function Person() {}
Person.prototype.test = "string";

function Man() {}

function inherit(superClass) {
    function F() {}
    F.prototype = superClass.prototype;
    return new F;
}

var t = inherit(Person);
console.log(t.test);

But you generally want to assign the returned object to another function's prototype:

Man.prototype = inherit(Person);

var m = new Man();
console.log(m.test);

...so that m.test also prints string, which means that objects created using Man are linked to Person's prototype).

Note that Man.prototype.prototype is undefined and -- this is the important part -- also meaningless. Functions have prototypes. Other objects (such as Man.prototype) do not. The prototype property is not magical in any other context. Assigning a value to a random object's prototype property doesn't do anything special. It's just another property.

Note also that the thing we returned from inherit is linked to Person by way of its prototype and has no access to any properties added to instances of Person.

like image 58
Wayne Avatar answered Jan 18 '23 23:01

Wayne