Sanjida lina
Sanjida lina

Reputation: 123

Can i call constructor function in javascript?

i have created a constructor function in javascript

function hello () {
    name = 'shahin';
    age= 22;
    mesg = function () {
        return 'My name is ' + this.name + 'and i am '+ this.age + 'old';
    }
}

console.log(hello.mesg());

and instead creating of new constructor from it i just wanted to whether it is working as a normal function or not. hence try with the console and see that error : "TypeError: hello.mesg is not a function.

`

function hello () {
    this.name = 'shahin';
    this.age= 22;
    this.mesg = function () {
        return 'My name is ' + this.name + ' and i am '+ this.age + ' years old';
    }
}

console.log(hello.mesg())

I even try with this and got the same error

Upvotes: 1

Views: 93

Answers (2)

moon
moon

Reputation: 670

To understand your question properly, you need to know the return value of a function.

(function(){
    var a = 1;
})();

This returns undefined, since there's no any return value designated.

(function(){
    var b = 2;    
    return b;
})();

This obviously returns b.

Can you distinguish the difference? So, the case #1 and case #2, hello function doesn't point anything as a return value, that's why it returns undefined and you couldn't be able to access mesg method.

To work this out properly, there're bunch of possible ways, I'll give you one of examples.

function hello() {
    var name = 'shahin';
    var age= 22;
    var mesg = function () {
        return 'My name is ' + name + 'and i am '+ age + ' old';
    };

    return {
        getName: mesg
    };
}

var func = hello();
func.getName(); // print 'My name is ... '

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

In the second case, mesg is the instance's variable of hello, you need to invoke it by instantiating with new operator.

console.log((new hello()).mesg())

In the first case, you can't invoke mesg as a property. You invoke mesg only if you return the mesg function

function hello () {
    name = 'shahin';
    age= 22;
    return mesg = function () {
        return 'My name is ' + this.name + 'and i am '+ this.age + 'old';
    }
}
console.log(hello()());

Upvotes: 0

Related Questions