在JavaScript中将字符串子类化 [英] Subclassing String in JavaScript

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

问题描述

我有一个字符串方法String.prototype.splitName(),它将作者的名字(字符串)分为名字和姓氏。语句var name = authorName.splitname();使用name.first = "..."name.last = "..."返回对象文字name(name的属性具有字符串值)。

最近有人告诉我,将splitName()作为公共字符串()类的方法是不明智的,但我应该使私有子类成为字符串的子类,并使用我的函数扩展子类(而不是公共类)。我的问题是:如何为字符串执行子类化,以便在将authorName赋给新的子类后name = authorName.splitname();仍然是有效的语句?如何将authorName赋给字符串的新私有子类?

推荐答案

https://gist.github.com/NV/282770启发,我回答自己的问题。在 下面的ECMAScript-5代码我定义了一个对象类"StringClone"。由(1)班级 从本机类"字符串"继承所有属性。的一个实例 "StringClone"是不能对其应用"字符串"方法的对象 不会有什么诡计。当应用字符串方法时,JavaScript将调用这些方法 "toString()"和/或"valueof()"。通过覆盖(2)中的这些方法, "StringClone"类的实例的行为类似于字符串。最后, 实例的属性Long变为只读,这就是为什么(3)是 已介绍。

// Define class StringClone
function StringClone(s) {
    this.value = s || '';
    Object.defineProperty(this, 'length', {get:
                function () { return this.value.length; }});    //(3)
};
StringClone.prototype = Object.create(String.prototype);        //(1)
StringClone.prototype.toString = StringClone.prototype.valueOf
                               = function(){return this.value}; //(2)

// Example, create instance author:
var author = new StringClone('John Doe');  
author.length;           // 8
author.toUpperCase();    // JOHN DOE

// Extend class with a trivial method
StringClone.prototype.splitName = function(){
     var name = {first: this.substr(0,4), last: this.substr(4) };
     return name;
}

author.splitName().first; // John
author.splitName().last;  // Doe

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

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