在Function.prototype.method中返回什么呢? [英] What does return this in Function.prototype.method do?
问题描述
我刚开始阅读JavaScript:好的部分,我已经对Function.prototype.method中的'返回'做了什么感到困惑?我理解这个和回归是如何运作的。 'this'本质上是当前对象的指针,'return'只是在输出一个值时退出函数,如果你描述的话;在我们的例子中,'this'。
I just started reading JavaScript: The Good Parts and I'm already confused by what 'return this' does in Function.prototype.method? I understand how 'this' and 'return' works. 'this' is essentially a pointer for the current object and 'return' simply exits the function while outputting a value if you described any; in our case, 'this'.
这是我引用的代码。
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'以查看代码是否会破坏但是它没有?究竟什么'回归'呢?我将继续阅读这本书,但我想确保我理解一切。任何帮助将不胜感激。
I tried omitting 'return this' to see if the code would break but it doesn't? What exactly does 'return this' do? I'll keep progressing through this book but I want to make sure I'm understanding everything. Any help will be appreciated.
推荐答案
它允许链接,所以你可以做这样的事情:
It allows for chaining so you can do something like this:
/* ADD METHODS */
Person.method('getName', function() { return this.name; })
.method('getAge', function() { return this.age; });
这篇关于在Function.prototype.method中返回什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!