扩展核心类型而无需修改原型 [英] Extending core types without modifying prototype

查看:137
本文介绍了扩展核心类型而无需修改原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不修改原型的情况下扩展核心JavaScript类型(String,Date等)?例如,假设我想用一些方便的方法创建一个派生的字符串类:

How does one extend core JavaScript types (String, Date, etc.) without modifying their prototypes? For example, suppose I wanted to make a derived string class with some convenience methods:

function MyString() { }
MyString.prototype = new String();
MyString.prototype.reverse = function() {
  return this.split('').reverse().join('');
};
var s = new MyString("Foobar"); // Hmm, where do we use the argument?
s.reverse();
// Chrome - TypeError: String.prototype.toString is not generic
// Firefox - TypeError: String.prototype.toString called on incompatible Object

错误似乎源自String基本方法,在这种情况下可能是拆分,因为它的方法正在应用于某些非字符串对象。但是,如果我们不能将其应用于非字符串对象,那么我们是否可以自动重复使用它们?

The error seems to originate from String base methods, probably "split" in this case, since its methods are being applied to some non-string object. But if we can't apply the to non-string objects then can we really reuse them automatically?

显然,我的尝试在很多方面存在缺陷,但我认为这证明了我的意图。经过一番思考后,似乎我们不能重用任何String原型对象的函数而不在String上显式调用它们。

Obviously my attempt is flawed in many ways but I think it demonstrates my intent. After some thinking, it seems that we can't reuse any of the String prototype object's functions without explicitly calling them on a String.

是否可以将核心类型扩展为这样?

Is it possible to extend core types as such?

推荐答案

2年后:在全球范围内改变任何事情都是一个可怕的想法

2 years later: mutating anything in global scope is a terrible idea

原文:

扩展原生原型存在错误是ES5中的FUD浏览器。

There being something "wrong" with extending native prototypes is FUD in ES5 browsers.

Object.defineProperty(String.prototype, "my_method", {
  value: function _my_method() { ... },
  configurable: true,
  enumerable: false,
  writeable: true
});

但是如果您必须支持ES3浏览器,那么使用的人会遇到问题for ... in 循环播放字符串。

However if you have to support ES3 browsers then there are problems with people using for ... in loops on strings.

我的意见是你可以改变原生原型并停止使用任何写得不好破解的代码

My opinion is that you can change native prototypes and should stop using any poorly written code that breaks

这篇关于扩展核心类型而无需修改原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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