2012-07-27 68 views
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 

参加工作后,我试着用在返回||但它不工作。谢谢您的帮助。

+0

你刚才问这个问题。您已经被告知返回值不能取决于链接到函数调用结束处的内容。 – 2012-07-27 23:26:41

+0

如果只有这个网站有版主... – 2012-07-27 23:31:07

+0

为什么downvote?他用清晰的话问了一些问题。如果这是一个好的或坏的事情是另一个历史。其他人可以稍后看到,并从这个问题中学习。人们对所有事情都赞不绝口,唉! – devundef 2012-07-27 23:34:00

回答

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 
+1

它与时间旅行。 – 2012-07-27 23:25:22

+0

感谢您的帮助。 – Shawn31313 2012-07-28 00:03:40

2

这是一个ackward建设,你想要什么,但是......

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/

+1

1+为例子(: – Shawn31313 2012-07-28 00:58:00