简体   繁体   English

有没有办法为单个变量扩展本机对象?

[英]Is there any way to extend an native object for a single variable?

I wanna get the next functionality: 我想获得下一个功能:

var newString = String;
newString.prototype.reverse = function () {
    return this.split("").reverse().join("")
}

var a = 'hello';
var b = newString('hello');
a.reverse();//reverse is not a function
b.reverse();//olleh

try extend .prototype before add function and doesn't work, i don't even know if it is possible. 尝试在添加功能之前扩展.prototype,并且不起作用,我什至不知道是否可能。

You could do the following: 您可以执行以下操作:

var newString = function(initialVal) {
    var val = new String(initialVal);
    val.reverse = function () {
        return this.split("").reverse().join("")
    };
    return val;
};

var a = 'hello';
var b = newString('hello');
a.reverse();//reverse is not a function
b.reverse();//olleh

It sounds like you're looking for: 听起来您正在寻找:

String.prototype.reverse = function () {
    return this.split("").reverse().join("")
}

var a = 'hello';
alert(a.reverse());

Note that extending built in objects like "String" is highly controversial at best. 请注意,扩展内置对象(例如“ String”)充其量是有争议的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM