4

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

Here's the code I'm referencing to.

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)

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.

4

2 に答える 2