0

我有这个返回对象的函数:

String.prototype.test = function(a,b){
    var ob = {};
    ob[a] = b;
    return this || ob
}

//usage
"Test".test('hi','hello');

如果.hi没有附加到测试,我希望它返回字符串。

因此,对于该示例,我需要:

"Test".test('hi','hello').hi;//returns: hello

工作,但我还需要:

"Test".test('hi','hello'); //returns Test

为了工作,我尝试||在退货中使用,但它不起作用。谢谢您的帮助。

4

2 回答 2

3

不可能使返回值取决于返回值发生的情况。

但是,您可以返回具有String属性的对象hi

不要在任何生产代码中这样做,它非常丑陋,没有人会想到它。

String.prototype.doStuffThatNobodyExpects = function(a, b) {
    var s = new String(this);
    s[a] = b;
    return s;
};

同样,不要在任何生产代码中这样做,它非常丑陋,没有人会想到它。

演示:

js> var s = 'Test'.doStuffThatNobodyExpects('hi', 'hello');
js> print(s);
Test
js> print(s.hi);
hello
于 2012-07-27T23:23:03.143 回答
2

这是您想要的结构,但是...

String.prototype.test = function(a,b){
    this[a]=b;
    return this;
}

//usage
document.write("Test".test('hi','hello'));
document.write("Test".test('hi','hello').hi);

jsFiddle: http: //jsfiddle.net/XUcYy/ ​</p>

于 2012-07-27T23:31:15.810 回答