2013-11-01 35 views
4

我刚开始阅读JavaScript:好的部分,我已经对Function.prototype.method中'return this'做了什么困惑?我明白'这个'和'回归'是如何工作的。 'this'基本上是当前对象的指针,'return'只是在输出值时退出函数,如果你描述了任何值;在我们的案例中,'这'。在Function.prototype.method中做什么返回呢?

下面是我引用的代码。

Function.prototype.method = function(name, func) { 
    this.prototype[name] = func; 
    return this; 
} 

/* SIMPLE CONSTRUCTOR */ 
function Person(name, age) { 
    this.name = name; 
    this.age = age; 
} 

/* ADD METHODS */ 
Person.method('getName', function() { return this.name; }); 
Person.method('getAge', function() { return this.age; }); 

var rclark = new Person('Ryan Clark', 22); 

console.log(rclark.getName()); // string(Ryan Clark) 
console.log(rclark.getAge()); // number(22) 

我试着省略'return this'来查看代码是否会中断但它不会? “返回这个”究竟做什么?我会继续阅读这本书,但我想确保我理解一切。任何帮助将不胜感激。

回答

4

它允许链接,所以你可以做这样的事情:

/* ADD METHODS */ 
Person.method('getName', function() { return this.name; }) 
     .method('getAge', function() { return this.age; }); 
+0

简单的A ++解释!就像jQuery如何在某些方面工作一样。 – W3Geek

+0

@ W3Geek我猜... – Neal

1

return this返回上method()被称为对象,并已通过添加传递方法将其修改后。

忽略它不会破坏你的代码,但它是一个更好的风格,让链接的方法调用,这样你就可以如:

Person.method('getName', function() { return this.name; }).method('getAge', function() { return this.age; }); 
+0

我从来没有真正想到这一点。这本书稍后会解释吗?如果'return this'被遗漏了,并且你尝试了链接,它会破坏你的代码,因为你会绞尽脑汁。 – W3Geek

+0

@ W3Geek我不知道这本书稍后会有解释,但我从经验中学到了这一点。 –