开发者

javascript function object's inherit method behaviour

I've come across a behaviour of the function object. that seems to be similar to prototyping but uses a different method.

var Car = function() {
    this.foo = 'shiny';
}

var Rover = function() {
    this.inherit = Car;
    this.inherit();
}

var Mini = function() {
    this.inher开发者_Python百科it = Car;
    this.inherit();
}

when a new instance of a sub class is made this.inherit method has the effect of calling the parent class on itself, so that the parent's properties and methods are available to the sub class.

var myRover = new Rover();

var myMini = new Mini();
myMini.foo = 'rusty';

console.log(myRover.foo, myMini.foo); // displays "shiny" & "rusty" respectively

I've looked in Mozilla and MSDN, but I can't seem to find it documented any where. Can anyone put a name to this behaviour and any further documentation.


I think the word inheritFrom does not make any sense here. It could be as well bar. What makes this work is the pattern that you define a member of the "subClass" function which you call on the next line.

It may be worth checking out "Classical Inheritance in JavaScript" article by Douglas Crockford for some additional ideas.


inheritFrom isn't a method that exists in JavaScript core objects. JavaScript inheritance can be accomplished in many ways as outlined in this post. What you're doing here is not really proper inheritance as you're just setting a single method in a separate object equal to a function.

First you declare a function called superClass. This function sets the foo and bar properties of the this object. When you set a method on subClass equal to superClass the this object then references the subClass function because it is the method's caller so then subClass has the properties of foo and bar set to 'foo' and 'bar'.

However, when you overwrite the foo method here:

this.foo = function() {
    return this.foo;
};

You turn foo into a function.

Notice that when you add this script:

var test = new subClass();
alert(test.foo);

test.foo will be a function as you overrode its value in the subClass constructor. Adding this:

alert(test.bar);

Will alert the string 'bar' since you didn't overwrite it. Also if you call test.foo() it will simply return a pointer to the test.foo method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜