Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

  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

    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); }
    };
    
like image 320
theateist Avatar asked Feb 25 '23 17:02

theateist


1 Answers

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

like image 69
Fareesh Vijayarangam Avatar answered Feb 27 '23 07:02

Fareesh Vijayarangam