JavaScript 中字符串的子类化

2024-02-01

我有一个字符串方法String.prototype.splitName()将作者姓名(字符串)拆分为名字和姓氏。该声明var name = authorName.splitname();返回一个对象字面量name with name.first = "..." and name.last = "..."(属性name有字符串值)。

最近我被告知这是不明智的splitName()作为一种方法publicString() 类,但我应该制作一个privateString 的子类并用我的函数扩展子类(而不是公共类)。我的问题是:如何对字符串执行子类化,以便在分配后authorName到新的子类name = authorName.splitname();仍然是一个有效的声明吗?我将如何分配authorName到 String 的新私有子类?


灵感来自https://gist.github.com/NV/282770 https://gist.github.com/NV/282770我回答我自己的问题。在里面 下面的 ECMAScript-5 代码我定义了一个对象类“StringClone”。按(1)类 继承本机类“String”的所有属性。一个实例 “StringClone”是一个不能应用“String”方法的对象 没有窍门。当应用字符串方法时,JavaScript 会调用该方法 “toString()”和/或“valueOf()”。通过重写 (2) 中的这些方法, “StringClone”类的实例的行为类似于字符串。最后, 实例的属性“length”变为只读,这就是为什么 (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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript 中字符串的子类化 的相关文章