What is the significance of the Javascript constructor property? - javascript

Trying to bend by head around Javascript's take on OO...and, like many others, running into confusion about the constructor property. In particular, the significance of the constructor property, as I can't seem to make it have any effect. E.g.:
function Foo(age) {
this.age = age;
}
function Bar() {
Foo.call(this, 42);
this.name = "baz";
}
Bar.prototype = Object.create(Foo.prototype);
var b = new Bar;
alert(b.constructor); // "Foo". That's OK because we inherit `Foo`'s prototype.
alert(b.name); // "baz". Shows that Bar() was called as constructor.
alert(b.age); // "42", inherited from `Foo`.
In the above example, the object b seems to have had the right constructor called (Bar) – and it inherits the age property from Foo. So why do many people suggest this as a necessary step:
Bar.prototype.constructor = Bar;
Clearly, the right Bar constructor was called when constructing b, so what impact does this prototype property have? I am curious to know what practical difference it actually makes to have the constructor property set 'correctly'—as I can't see it having any affect on which constructor is actually called after an object is created.

Step one is to understand what constructor and prototype are all about. It's not difficult, but one has to let go of "inheritance" in the classical sense.
The constructor
The constructor property does not cause any particular effects in your program, except that you can look at it to see which function was used in conjunction with the operator new to create your object. If you typed new Bar() it will be Bar and you typed new Fooit will be Foo.
The prototype
The prototype property is used for lookup in case the object in question does not have the property asked for. If you write x.attr, JavaScript will try to find attr among x's attributes. If it cant find it, it will look in x.__proto__. If it's not there either, it will look in x.__proto__.__proto__ and so on as long as __proto__ is defined.
So what is __proto__and what has it got to do with prototype? Shortly put, prototype is for "types" while __proto__ is for "instances". (I say that with quotation marks because there's not really any difference between types and instances). When you write x = new MyType(), what happens (among other things) is that x.__proto___ is set to MyType.prototype.
The question
Now, the above should be all you need to derive what your own example means, but to try and answer your actual question; "why write something like":
Bar.prototype.constructor = Bar;
I personally have never seen it and I find it a little silly, but in the context you've given it will mean that the Bar.prototype-object (created by using new Foo(42)) will pose as have being created by Bar rather than Foo. I suppose the idea is some make something similar to C++/Java/C#-like languages where a type-lookup (the constructor property) will always yield the most specific type rather than the type of the more generic object further up in the prototype-chain.
My advice: don't think very much about "inheritance" in JavaScript. The concepts of interfaces and mixins makes more sense. And don't check objects for their types. Check for the required properties instead ("if it walks like a duck and quacks like a duck, it's a duck").
Trying to force JavaScript into a classical inheritance model, when all that it has is the prototype-mechanism as described above, is what causes the confusion. The many people that suggested to manually set the constructor-property probably tried to do just that. Abstractions are fine, but this manual assignment of the constructor property is not very idiomatic usage of JavaScript.

September 2020 Update
The answer below is from the days of ECMAScript 3 and the first sentence is no longer true because since ECMAScript 6, the constructor property is used in a few places. However, I think the overall gist still applies. Thanks to T. J. Crowder for pointing that out in the comments, and please read his answer for a fuller picture of the current situation.
Original answer
The constructor property makes absolutely no practical difference to anything internally. It's only any use if your code explicitly uses it. For example, you may decide you need each of your objects to have a reference to the actual constructor function that created it; if so, you'll need to set the constructor property explicitly when you set up inheritance by assigning an object to a constructor function's prototype property, as in your example.

one case to use constructor:
this is one of the common realization of inheritance:
Function.prototype.extend = function(superClass,override) {
var f = new Function();
f.prototype = superClass.prototype;
var p = this.prototype = new f();
p.constructor = this;
this.superclass = superClass.prototype;
...
};
this new f() would not call the constructor of superClass,so when you create a subClass,maybe you need call the superClass at first,like this:
SubClass = function() {
SubClass.superClass.constructor.call(this);
};
so the constructor property make sense here.

The previous answers here say (in various ways) that the value of the constructor property isn't used by anything in JavaScript itself. That was true when those answers were written, but ES2015 and onward have started using constructor for things.
The constructor property of the prototype property of a function is meant to point back to the function so that you can ask an object what constructed it. It's set up automatically as part of creating a traditional function object or a class constructor object (details).
function TraditionalFunction() {
}
console.log(TraditionalFunction.prototype.constructor === TraditionalFunction); // true
class ExampleClass {
}
console.log(ExampleClass.prototype.constructor === ExampleClass); // true
Arrow functions don't have a prototype property, so they don't have prototype.constructor.
For years the JavaScript specification only said that the constructor property would be there and have that value (a link back to the function) by default. But starting in ES2015, that changed, and various operations in the specification now actually use the constructor property, such as this, this, this, and this.
So when setting up constructor functions that build inheritance chains, it's best to ensure that the constructor property is referring to the appropriate function. See my answer here for examples, etc.

One of the use cases when you would want the prototype.constructor property to survive prototype property reassignment is when you define a method on the prototype that produces new instances of the same type as the given instance. Example:
function Car() { }
Car.prototype.orderOneLikeThis = function() { // Clone producing function
return new this.constructor();
}
Car.prototype.advertise = function () {
console.log("I am a generic car.");
}
function BMW() { }
BMW.prototype = Object.create(Car.prototype);
BMW.prototype.constructor = BMW; // Resetting the constructor property
BMW.prototype.advertise = function () {
console.log("I am BMW with lots of uber features.");
}
var x5 = new BMW();
var myNewToy = x5.orderOneLikeThis();
myNewToy.advertise(); // => "I am BMW ..." if `BMW.prototype.constructor = BMW;` is not
// commented; "I am a generic car." otherwise.

The constructor property points to the constructor that was used to create the object instance. If you typed 'new Bar()' it will be 'Bar' and you typed 'new Foo()' it will be 'Foo'.
But if you set the prototype without setting the constructor, you would get something like this:
function Foo(age) {
this.age = age;
}
function Bar() {
this.name = "baz";
}
Bar.prototype = new Foo(42);
var one = new Bar();
console.log(one.constructor); // 'Foo'
var two = new Foo();
console.log(two.constructor); // 'Foo'
To set the constructor actually to the constructor that was used to create the object, we need to set the constructor as well while setting prototype as follows:
function Foo(age) {
this.age = age;
}
function Bar() {
this.name = "baz";
}
Bar.prototype = new Foo(42);
Bar.prototype.constructor = Bar;
var one = new Bar();
console.log(one.constructor); // 'Bar'
var two = new Foo();
console.log(two.constructor); // 'Foo'

Related

What harm can omitting prototype.constructor cause when inheriting? [duplicate]

Trying to bend by head around Javascript's take on OO...and, like many others, running into confusion about the constructor property. In particular, the significance of the constructor property, as I can't seem to make it have any effect. E.g.:
function Foo(age) {
this.age = age;
}
function Bar() {
Foo.call(this, 42);
this.name = "baz";
}
Bar.prototype = Object.create(Foo.prototype);
var b = new Bar;
alert(b.constructor); // "Foo". That's OK because we inherit `Foo`'s prototype.
alert(b.name); // "baz". Shows that Bar() was called as constructor.
alert(b.age); // "42", inherited from `Foo`.
In the above example, the object b seems to have had the right constructor called (Bar) – and it inherits the age property from Foo. So why do many people suggest this as a necessary step:
Bar.prototype.constructor = Bar;
Clearly, the right Bar constructor was called when constructing b, so what impact does this prototype property have? I am curious to know what practical difference it actually makes to have the constructor property set 'correctly'—as I can't see it having any affect on which constructor is actually called after an object is created.
Step one is to understand what constructor and prototype are all about. It's not difficult, but one has to let go of "inheritance" in the classical sense.
The constructor
The constructor property does not cause any particular effects in your program, except that you can look at it to see which function was used in conjunction with the operator new to create your object. If you typed new Bar() it will be Bar and you typed new Fooit will be Foo.
The prototype
The prototype property is used for lookup in case the object in question does not have the property asked for. If you write x.attr, JavaScript will try to find attr among x's attributes. If it cant find it, it will look in x.__proto__. If it's not there either, it will look in x.__proto__.__proto__ and so on as long as __proto__ is defined.
So what is __proto__and what has it got to do with prototype? Shortly put, prototype is for "types" while __proto__ is for "instances". (I say that with quotation marks because there's not really any difference between types and instances). When you write x = new MyType(), what happens (among other things) is that x.__proto___ is set to MyType.prototype.
The question
Now, the above should be all you need to derive what your own example means, but to try and answer your actual question; "why write something like":
Bar.prototype.constructor = Bar;
I personally have never seen it and I find it a little silly, but in the context you've given it will mean that the Bar.prototype-object (created by using new Foo(42)) will pose as have being created by Bar rather than Foo. I suppose the idea is some make something similar to C++/Java/C#-like languages where a type-lookup (the constructor property) will always yield the most specific type rather than the type of the more generic object further up in the prototype-chain.
My advice: don't think very much about "inheritance" in JavaScript. The concepts of interfaces and mixins makes more sense. And don't check objects for their types. Check for the required properties instead ("if it walks like a duck and quacks like a duck, it's a duck").
Trying to force JavaScript into a classical inheritance model, when all that it has is the prototype-mechanism as described above, is what causes the confusion. The many people that suggested to manually set the constructor-property probably tried to do just that. Abstractions are fine, but this manual assignment of the constructor property is not very idiomatic usage of JavaScript.
September 2020 Update
The answer below is from the days of ECMAScript 3 and the first sentence is no longer true because since ECMAScript 6, the constructor property is used in a few places. However, I think the overall gist still applies. Thanks to T. J. Crowder for pointing that out in the comments, and please read his answer for a fuller picture of the current situation.
Original answer
The constructor property makes absolutely no practical difference to anything internally. It's only any use if your code explicitly uses it. For example, you may decide you need each of your objects to have a reference to the actual constructor function that created it; if so, you'll need to set the constructor property explicitly when you set up inheritance by assigning an object to a constructor function's prototype property, as in your example.
one case to use constructor:
this is one of the common realization of inheritance:
Function.prototype.extend = function(superClass,override) {
var f = new Function();
f.prototype = superClass.prototype;
var p = this.prototype = new f();
p.constructor = this;
this.superclass = superClass.prototype;
...
};
this new f() would not call the constructor of superClass,so when you create a subClass,maybe you need call the superClass at first,like this:
SubClass = function() {
SubClass.superClass.constructor.call(this);
};
so the constructor property make sense here.
The previous answers here say (in various ways) that the value of the constructor property isn't used by anything in JavaScript itself. That was true when those answers were written, but ES2015 and onward have started using constructor for things.
The constructor property of the prototype property of a function is meant to point back to the function so that you can ask an object what constructed it. It's set up automatically as part of creating a traditional function object or a class constructor object (details).
function TraditionalFunction() {
}
console.log(TraditionalFunction.prototype.constructor === TraditionalFunction); // true
class ExampleClass {
}
console.log(ExampleClass.prototype.constructor === ExampleClass); // true
Arrow functions don't have a prototype property, so they don't have prototype.constructor.
For years the JavaScript specification only said that the constructor property would be there and have that value (a link back to the function) by default. But starting in ES2015, that changed, and various operations in the specification now actually use the constructor property, such as this, this, this, and this.
So when setting up constructor functions that build inheritance chains, it's best to ensure that the constructor property is referring to the appropriate function. See my answer here for examples, etc.
One of the use cases when you would want the prototype.constructor property to survive prototype property reassignment is when you define a method on the prototype that produces new instances of the same type as the given instance. Example:
function Car() { }
Car.prototype.orderOneLikeThis = function() { // Clone producing function
return new this.constructor();
}
Car.prototype.advertise = function () {
console.log("I am a generic car.");
}
function BMW() { }
BMW.prototype = Object.create(Car.prototype);
BMW.prototype.constructor = BMW; // Resetting the constructor property
BMW.prototype.advertise = function () {
console.log("I am BMW with lots of uber features.");
}
var x5 = new BMW();
var myNewToy = x5.orderOneLikeThis();
myNewToy.advertise(); // => "I am BMW ..." if `BMW.prototype.constructor = BMW;` is not
// commented; "I am a generic car." otherwise.
The constructor property points to the constructor that was used to create the object instance. If you typed 'new Bar()' it will be 'Bar' and you typed 'new Foo()' it will be 'Foo'.
But if you set the prototype without setting the constructor, you would get something like this:
function Foo(age) {
this.age = age;
}
function Bar() {
this.name = "baz";
}
Bar.prototype = new Foo(42);
var one = new Bar();
console.log(one.constructor); // 'Foo'
var two = new Foo();
console.log(two.constructor); // 'Foo'
To set the constructor actually to the constructor that was used to create the object, we need to set the constructor as well while setting prototype as follows:
function Foo(age) {
this.age = age;
}
function Bar() {
this.name = "baz";
}
Bar.prototype = new Foo(42);
Bar.prototype.constructor = Bar;
var one = new Bar();
console.log(one.constructor); // 'Bar'
var two = new Foo();
console.log(two.constructor); // 'Foo'

Purpose of this Javascript prototype snippet

Sorry I can't phrase this better. But I ran across some code like the following:
MyObject.prototype = Object.create(MyObject.prototype);
MyObject.prototype.constructor = MyObject;
And I just can't seem to figure out what it does. MyObject is defined above it something like this:
function MyObject(options) {
this.someProp = someDefault;
this.otherProp = process(options.something);
// etc...
}
and it's always called as a constructor. I'm just wondering what benefit those first two lines provide and if it's a known pattern in Javascript.
I just can't seem to figure out what it does
It creates a new object that inherits from [the old] MyObject.prototype via Object.create and then overwrites MyObject.prototype with that. It also explicitly adds a .constructor property which actually should be existing already.
I'm just wondering what benefit those first two lines provide
None, unless before that snippet someone has corrupted the prototype (like MyObject.prototype = Object.prototype) and this is an attempt to fix it.
…and if it's a known pattern in Javascript.
Not like this. Using Object.create to set up the prototype chain for inheritance between constructor-defined "classes" is a known pattern, but then the constructors would be different on each side of the assignment.
The two lines of code provided seem to be an incorrect attempt of the use of prototypal inheritance, but I see where you're going with this and what you're trying to accomplish.
As we know, there are two ways in JavaScript to define objects that have properties and methods as members - the object literal notation and function notation. Using object literal notation, we don't have immediate access to the new keyword (think of this like using abstract classes in Java or C#). With function notation, we have access to the new keyword because the initial declaration of an object as a function serves as our constructor.
In ECMAScript 5, The Object object was given a method called create that provided developers a simple way to create a new object from an existing object declared with the object literal notation. (See documentation here). However, objects created in function notation have problems with this method because they are Function objects. The Object.create method is a great way to use simple inheritance, allowing access to the base properties and methods.
With function notation, once the new keyword is used, the result is not a function, but rather an object. For example, I can test this:
var Obj = function(){};
console.log(typeof Obj) // "function"
console.log(typeof new Object()); // "object"
Because of this, you can only inherit once (meaning the child object cannot be derived from):
var MyObject = new Object();
var anotherObj = new MyObject() // throws exception
To alleviate this problem, you need to follow three steps:
Create your child object in function notation (so you can create new instances of it using the new keyword and inherit from it).
Set the child object's prototype (an object) to the result of a new instance of the base object (which will be an object as well).
Set the constructor of the child object (which happens to be on the object's prototype) back to reference the Function of itself (which is a function prior to instantiation). If you don't do this, the constructor will remain an object, which cannot spawn new instances.
From here, you can create new instances of both the child and parent objects and derive from both, using the pattern. Here's a practical example:
var Vehicle = function(){};
Vehicle.prototype.start = function() {
return this.make + " " + this.model + " " + "started";
}
var Car = function(color, make, model) {
this.color = color;
this.make = make;
this.model = model;
}
Car.prototype = new Vehicle();
Car.prototype.constructor = Car;
var myCar = new Car("red", "chevy", "aveo");
myCar.start(); //"chevy aveo started"
I really don't see any benefit in doing that.
What it's doing is providing the new object with the previous objects methods. But it's coming from the same object...
Here is a good example of JS inheritance:
http://jsfiddle.net/aDCmA/2/
var App = (function(){
var Being = function() {
this.living = true;
this.breathes = function () {
return true;
};
};
var Robert = function() {
this.blogs = true;
this.getsBored = function () {
return "You betcha";
}
};
Robert.prototype = new Being();
return {
Being: Being,
Robert: Robert,
being: function(){ return new Being(); },
robert: function(){ return new Robert(); }
}
}());
Here is another question that is similar: inherit prototype methods from other classes without overriding own prototype methods
Credit to Robert Nyman for originally blogging about it: http://robertnyman.com/2008/10/06/javascript-inheritance-how-and-why/
Let's see line by line:
MyObject.prototype = Object.create(MyObject.prototype);
This redefines MyObject.prototype to an object that inherits from MyObject.prototype. This is unusual, because it makes no sense to inherit from itself.
MyObject.prototype.constructor = MyObject;
Since the previous line overwrote MyObject.prototype, this is just fixing the constructor property that was lost in the process.
I can think of one scenario where tht might be useful: if some code before that messed up with MyObject.prototype, for example assigning the prototype of another constructor to it:
MyObject.prototype = SomethingElse.prototype; // wrong way to do inheritance.
Then the code you posted would be an attempt to fix it.
This is perfectly valid Javascript.
Any javascript function (say Func)can be used as a constructor and the constructor invocation also requires a prototype property (i.e. F.prototype or the prototype associated with the function) . Thus (almost) every function has a prototype property. The value of this property (i.e. Func.prototype).
Now the value of this prototype associated with the function is an object itself that has a single non enumerable property called constructor. And the value of this constructor property is the function object (i.e. F itself).
Lets take an example.
Say I construct a function Func
var Func = function() {
//your definition
};
Now since this can be invoked as a constructor it has to have a prototype property Func.prototype lets call this proto.
proto = Func.prototype;
Now the prototype has a single property (that is non enumerable) called constructor. This constructor has a value that is equal to the function object itself.
Dont believe me check it like this
Func.prototype.constructor === Func // =>true
Will always return true for any function.
Now from the code you explained :
So basically these two lines
MyObject.prototype = Object.create(MyObject.prototype);
MyObject.prototype.constructor = MyObject;
are modifying the value of the prototye to have a constructor property with the value of MyObject that is defined. But that would have happened anyways in the normal course of things. But the reason could be that maybe the prototype of the object has been changed earlier from the class it has been inherited from. In that case would those two lines make sense.
Hope that helps :)

Is there a good use case for the constructor property in Javascript?

First off, this question is not "what does the constructor property do?" - There's plenty of good documentation on exactly what it is and how it works: It's a reference to the function that created the object (which may be inherited from its prototype).
I'm more interested in knowing common use-cases for this property. It seems all good in theory, but when would you actually need a reference to the function that constructed your object? A few ideas would be:
Perhaps I want to clone it. I could call the constructor again and
get another instance of my object. This of course wouldn't work well
since you'd potentially be creating an instance of your object's
prototype, not the object itself; plus a much preferred method would
be to create a new object and set that object's prototype instead.
Perhaps you can use it to figure out what the "type" of the object
is. This seems rather odd, since you can use instanceof or
Object.prototype.toString() instead.
Can you change or re-assign the constructor? Would there ever be a good reason to
do this?
Hopefully some people can chime in with some good Javascript paterns that make use of the constructor reference, or provide an official explanation for why the property exists.
One case where the constructor property is handy (or would be if it was reliable) is where a function needs to know the type of argument it has been passed, e.g.
function foo(arg) {
if ( /* if arg is an array */ ) {
// deal with array
} else if ( /* if arg is an object */ ) {
// deal with object
}
}
If the above function is passed an array or object, then typeof will return object in both cases. The constructor property can be used:
if ( arg.constructor == Array )
But that fails if the array is created in a different frame to where the test is taking place (i.e. it's Array constructor is a different object to the Array function in the scope of the test).
So if you rule out frames (or other cases where scope is an issue), then the constructor property is fine to use for this.
But that does not fix the general issue of the constructor property being writable (and therefore can be set to anything) and cases where the prototype chain is more than trivial.
One of the good use cases is implementation of "inheritance" and "classes in javascript. Let's consider the following example:
// define the Person Class
function Person() {}
Person.prototype.walk = function(){
alert ('I am walking!');
};
Person.prototype.sayHello = function(){
alert ('hello');
};
// define the Student class
function Student() {
// Call the parent constructor
Person.call(this);
}
// inherit Person
Student.prototype = new Person();
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
// replace the sayHello method
Student.prototype.sayHello = function(){
alert('hi, I am a student');
}
// add sayGoodBye method
Student.prototype.sayGoodBye = function(){
alert('goodBye');
}
var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();
// check inheritance
alert(student1 instanceof Person); // true
alert(student1 instanceof Student); // true
As you can see we've inherited Person, by reassigning Student.prototype to new Person();, but then we need to reassign constructor back to Student as we want to create instance of Student class, but not a Person.
UPDATE
Btw, more real-world example of inheritance in javascript is to use intermediate function, so Person object will not be created during definition stage:
// inherit Person
function F() {}
F.prototype = Person.prototype;
Student.prototype = new F();
I've used it before for type checking. It's not much more useful than instanceof, but it's a little more explicit.
function isArray(o) {
return o.constructor == Array;
}

What's the difference between 2 JavaScript objects?

I try do improve my JavaScript skills.
I don't understand why (5) works and (2) returns error. Isn't the same?
B.fn() //OK
B.fn2() //TypeError: Object # has no method 'fn2'
var a = new A()
a.fn() //OK
a.fn2() //OK
var A = function () {
this.fn = function () { alert(3); }
}
A.prototype = {
fn2: function () { alert(4); }
};
var B =
{
fn: function () { alert(1); }
}
B.prototype = {
fn2: function () { alert(2); }
};
a is an instance of the A class, where as B is the class itself. Since fn2 is not defined as static function, it will only be available to an instance of class B as opposed to the class B itself.
If you wanted to use B directly, you could use:
new B().fn2()
if you define B as a function()
Alternatively, you could define fn2 the same way you have defined fn
(easy explanation)
The prototype property only applies when using a function as constructor (by using the new operator). The function creates a clone of it's prototype and the this keyword inside the function is set to the clone. The properties on the clone are direct references/pointers to the prototypes properties.
The object literal {} is a more powerfull expression alternative to new Object() and as such "inherits" properties from Object.prototype.
So:
function ClassLike() {}
ClassLike.prototype = {
foo : "bar"
}
var instance = new ClassLike();
alert( instance.foo ); // bar
Works because the new operator kicks some operations in motion to create a new object whereas:
var instance = {
foo : "bar"
}
instance.prototype = {
baz : "foobar"
}
Merely adds another property (prototype) to an already created object and no process is put in motion to actually assign/change the objects original prototype.
Now Mozilla has added a non standard (IE does not support it) way to change an already instantiated objects prototype through __proto__ and there are some petitions going to add it to ES5 (EcmaScript 5). I would not use it atm. but it works like this:
var instance = {};
var parent = {
foo : "bar"
}
instance.__proto__ = parent;
alert( instance.foo ); // bar
Another way to change an already instantiated object's prototype is to add to the Object constructors prototype (which is not advised for many reasons). As such:
var instance = {}; // a more powerful alternative to `new Object()`
Object.prototype.foo = "bar";
alert( instance.foo ); // bar
It's all possible, though wether it's wise to do it... I'd say no, but opinions vary and I rather avoid the debate ;)
Anyways, just remember that the prototype property on works when you new a function, otherwise it just becomes a property on the instance.
What you have demonstrated is caused by something that I would consider the biggest problem with OO in JavaScript: prototype must be a property of the constructor function and not the object itself. It means that if you have a single object that can be easily defined as an object literal, you still need to have a useless constructor just to define the prototype of your object.
Read this article: Prototypal Inheritance in JavaScript by Douglas Crockford. Here is the relevant part:
[...] JavaScript itself is conflicted
about its prototypal nature. In a
prototypal system, objects inherit
from objects. JavaScript, however,
lacks an operator that performs that
operation. Instead it has a new
operator, such that new f() produces
a new object that inherits from
f.prototype This indirection was
intended to make the language seem
more familiar to classically trained
programmers, but failed to do that, as
we can see from the very low opinion
Java programmers have of JavaScript.
JavaScript's constructor pattern did
not appeal to the classical crowd. It
also obscured JavaScript's true
prototypal nature. As a result, there
are very few programmers who know how
to use the language effectively.
Fortunately, it is easy to create an
operator that implements true
prototypal inheritance. It is a
standard feature in my toolkit, and I
highly recommend it for yours.
Read the article for some ideas no how to effectively solve what you are trying to do.
Well, your answer is pretty simple.In JavaScript, only constructors have "prototypes" i.e. the prototype property. Object literals e.g "{}" don't. Therefore, your number 2 will never work unless you change it as follows:
var B = function(){ // the B constructor
return this;
}
B.prototype = {
fn2: function(){ alert(2); }
}

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.inherit = 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.

Categories

Resources