Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I try do improve my JavaScript skills. I don't understand why (5) works and (2) returns error. Isn't the same?

(1) - B.fn() //OK
(2) - B.fn2() //TypeError: Object # has no method 'fn2';
(3) - var a = new A()
(4) - a.fn() //OK
(5) - a.fn2() //OK

C#
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); }
};
Posted
Updated 21-Mar-11 22:34pm
v2

1 solution

Your B object wasn't initialised using the new keyword. When you initialise an object using the new keyword, the functions on the prototype will be applied to the resulting object. The correct way to define a class in JavaScript is:

A = function() {
    //This is the constructor. 
};

A.prototype = {
    //This prototype object contains a definition of the functions on your class.
    fn: function() {
        alert(1);
    }
};


You then instantiate an object in this way;
var a = new A();
a.fn();


I recommend you read some of Douglas Crockford's tutorials[^].
 
Share this answer
 
Comments
Sandeep Mewara 22-Mar-11 5:29am    
Great answer. My 5!
Manfred Rudolf Bihy 22-Mar-11 5:29am    
My 5!
Proposed as solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900