Javascript function return object, return this和没有return的差别

Function在javascript里面可以实例化,也可以直接调用。

作为直接调用对象时,它会执行这个function并得到相应的返回值。

function makeGamePlayer(name,totalScore,gamesPlayed) {
    var obj = {
        name: name,
        totalScore: totalScore,
        gamesPlayed: gamesPlayed
    }
    return obj;
}

var player = makeGamePlayer("John Smith", 15, 3);

在这种情况下,不加return会返回undefined,return this返回window对象。

作为实例化对象时,它会执行下列操作:

  1. Creates a new object which inherits from the .prototype of the constructor
  2. Calls the constructor passing this object as the this value
  3. It returns the value returned by the constructor if it's an object, or the object created at step 1 otherwise.
function makeGamePlayer(name,totalScore,gamesPlayed) {
    this.name =  name;
    this.totalScore = totalScore;
    this.gamesPlayed = gamesPlayed;
}

var player = new GamePlayer("John Smith", 15, 3);

在这种情况下,return this和不加return是一样的,返回的都是step 1创建的对象,也就是实例本身。

参考链接:

http://stackoverflow.com/questions/12272239/javascript-function-returning-an-object