Crockford 的《JavaScript the Good Parts》一书讨论了增强基本类型的函数。他的函数如下所示:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
}
我不明白这里如何/为什么使用“this”变量。我仅在使用“new”调用该函数时使用“this”,但该函数的调用方式如下:
Number.method('integer', function () {
return Math[this < 0 ? 'ceil' : 'floor'](this)
});
最佳答案
this
指的是函数在调用时引用的对象。
var obj = {fn: function() {return this;}};
obj.fn(); // obj
var fn = obj.fn;
fn(); // window or null or error
fn.call(obj); // obj
fn.apply(obj); // obj
method 位于 Function.prototype
上,这意味着所有 Function 实例都继承 method 和 this
预计会引用您正在调用它的函数实例,即method
内的
Function.prototype.getThis = function () {return this;};
function hello() {}
hello.getThis(); // hello
// and consequently
hello.getThis().getThis().getThis().getThis().getThis(); // hello
构造函数也是函数。因此,所有构造函数都会继承该方法。因此,这里的方法示例意味着“将属性name
添加到由this
(构造函数)实例继承的原型(prototype)中,并设置该属性的值到 func
,然后返回构造函数,以便您可以链接它”
function Foo() {}
Foo.method('bar', 'baz').method('fizz', 'buzz'); // Foo
var foo = new Foo();
foo.bar; // "baz", inherited from Foo.prototype
foo.fizz; // "buzz", inherited from Foo.prototype
关于javascript - 'return this' 在增加类型时会做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31436827/