在JavaScript中扩充类型 [英] Augmenting types in JavaScript

查看:99
本文介绍了在JavaScript中扩充类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Douglas Crockford的 JavaScript:The Good Parts ,我对某些事情感到有些困惑。在第4章的扩充类型下,他创建了一个添加方法的快捷方式。

I'm reading Douglas Crockford's JavaScript: The Good Parts, and I'm a little confused about something. In chapter 4, under Augmenting Types, he creates a shortcut for adding a method.

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

他说:


通过使用'method'方法扩充Function.prototype,我们不再需要
来键入prototype属性的名称。现在可以隐藏那些丑陋的

By augmenting Function.prototype with a 'method' method, we no longer have to type the name of the prototype property. That bit of ugliness can now be hidden.

然后他继续使用它来添加'整数'方法用这个数字原型。

He then goes on to use this to add an 'integer' method to the number prototype with this.

Number.method('integer', function () {
    return Math[this < 0 ? 'ceil' : 'floor'](this);
});

document.writeln((-10 / 3).integer()); // -3

我在这里有点困惑...因为我们添加了'方法' Function 原型的方法,而不是Number原型。据我所知,Number对象不会从Function原型继承(虽然我可能在那里错了)。我看到这有效,但我不明白为什么Number对象能够使用这个'方法'方法来添加...方法。

I'm a little confused here... because we added a 'method' method to the Function prototype, not the Number prototype. And to my knowledge, the Number object does not inherit from the Function prototype (though maybe I'm wrong there). I see that this works, but I don't understand why Number objects are able to make use of this 'method' method to add... methods.

推荐答案

我认为这是有效的,因为数字 一个函数。

I assume this works because Number is a function.

如下所示: http://jsfiddle.net/zCbdB/1

这篇关于在JavaScript中扩充类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆