以下javascript代码中是否需要return语句?

时间:2017-07-03 13:26:46

标签: javascript

var Greeting = (function () {
    function Greeting() {
    }
    Greeting.prototype.greet = function () {
      console.log("Hello World!!!");
    };
	 return Greeting;
    }());

var obj = new Greeting();
obj.greet()

如果我删除return语句,则表示obj.greet()不是函数。

1 个答案:

答案 0 :(得分:0)

返回语句是必需的,因为您已创建“私有”范围。

// GlobalScope: You create a variable named `Greeting`
var Greeting = (function() {
    // PrivateScope: You create a function named `Greeting`
    function Greeting() {}

    // PrivateScope: You create a method on the Greeting prototype
    Greeting.prototype.greet = function() {
        console.log("Hello World!!!");
    };

    // PrivateScope: You tell your function to return your "private" scoped `Greeting`
    return Greeting;
}());

您可以在没有“私人”范围的情况下表达相同的代码,然后您将不需要return声明。

function Greeting() {}

Greeting.prototype.greet = function() {
  console.log("Hello World!!!");
};

var obj = new Greeting();
obj.greet()