Sleepyhead
Sleepyhead

Reputation: 103

What is the output of the following javascript code and why?

I am really new in JavaScript. Can you please explain what should be the output of the following JavaScript Code? Please explain the reason as detail as possible. Thank you so much.

var Foo = function( a ) { 
    function bar() {   
        return a; 
    }
    this.baz = function() {   
        return a; 
    };
};

Foo.prototype = {
    biz: function() {    
        return a; 
    }        
};

var f = new Foo( 7 );
f.bar(); 
f.baz(); 
f.biz(); 

Upvotes: 0

Views: 1744

Answers (3)

Khalid Azam
Khalid Azam

Reputation: 1643

you can do as below.

var Foo = function( a ) { 
  this.a = a;
    this.bar = function() {   
        return this.a; 
    }
    this.baz = function() {   
        return this.a; 
    };
};

Foo.prototype = {
    biz: function() {    
        return this.a; 
    }        
};

var f = new Foo( 7 );
console.log(f.bar()); 
console.log(f.baz()); 
console.log(f.biz()); 

Upvotes: 0

rasmeister
rasmeister

Reputation: 1996

The result is an error. f.bar is not a function. That is because it is a local function with scope only within the Foo function. It is effectively a private function only available within the function it is defined in.

When you call new Foo(), you are invoking the function as a constructor. This will create an object and return it. Within the function that object can be referenced as 'this'. Since baz is added as a property to the this object, it will be included in the object created when you do f = new Foo(7).

baz is available since it is part of the constructed object when you do new Foo().

f.biz() is also available since it is placed in Foo's prototype. Adding a prototype meaning it is shared by all instances of Foo (f being one of them).

The variable a is only defined within the constructor function, so it will be undefined in the biz() function call. Consequently, f.biz() will return undefined.

Upvotes: 7

Matthew
Matthew

Reputation: 962

Not only will this throw an error since f.bar() is only accessible inside the Foo function scope (eg its basically a "private" method), but also all of the methods (bar, baz, biz) reference the property "a" which isnt actually defined as a property of Foo instances.

You should be storing "a" inside Foo using this.a = a, and accessing it inside your Foo methods (bar, baz, biz) using return this.a

Upvotes: 1

Related Questions