'返回this'在增加类型时执行

What does 'return this' do when augmenting types?

本文关键字:执行 类型 this 返回 增加      更新时间:2023-09-26

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

方法Function.prototype上,这意味着所有函数实例继承方法method中的this预计会引用您正在调用它的函数实例,即

Function.prototype.getThis = function () {return this;};
function hello() {}
hello.getThis(); // hello
// and consequently
hello.getThis().getThis().getThis().getThis().getThis(); // hello

构造函数也是函数。因此所有构造函数都继承方法方法在这里的例子意味着"添加一个属性name到由this(构造函数)的实例继承的原型中,并将该属性的值设置为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

this是指它的执行上下文。更准确地说,在函数内部使用,并指向调用它的对象

相关文章: