我可以在javascript中调用构造函数吗?

时间:2017-11-27 13:40:21

标签: javascript

我在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());

而是从它创建新的构造函数我只是想它是否作为正常函数工作。因此尝试使用控制台并看到该错误:“TypeError:hello.mesg不是函数。

`

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())

我甚至尝试过这个并得到同样的错误

2 个答案:

答案 0 :(得分:1)

要正确理解您的问题,您需要知道函数的返回值。

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

返回 undefined ,因为没有指定任何返回值。

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

这显然会返回 b

你能区分出差异吗?因此,情况#1和情况#2,hello函数不会将任何内容指向返回值,这就是为什么它返回 undefined 并且您无法访问 mesg 方法。

要正确地解决这个问题,有很多可能的方法,我会给你一个例子。

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 ... '

答案 1 :(得分:0)

在第二种情况中,mesghello的实例变量,您需要通过使用new运算符进行实例化来调用它。

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

在第一种情况中,您无法将mesg作为属性调用。只有在返回mesg函数时才调用mesg

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