在JavaScript中将字符串子类化子类、字符串、中将、JavaScript

2023-09-03 09:02:26 作者:長樂.

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

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

推荐答案

云计算开发实例 Python3将字符串的时间转换为时间戳

受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