2017-09-29 14 views
3

我試圖返回調用該函數的字符串。如何從原型返回輸入如果爲false

但它不返回字符串......它返回一個數組。

String.prototype.testing = function testing() { 
 
    if (this === "what") {} 
 
    return this //Should return - this is a string 
 
} 
 

 

 
x = "this is a string" 
 

 
y = x.testing() 
 

 
console.log(y)

+0

定義它是'this'是一個字符串? –

+0

x是調用函數的那個​​...所以不是這個被認爲是x的嗎? –

+0

和x是「這是一個字符串」 –

回答

9

JavaScript有兩個String對象和字符串元。在鬆散模式下的String.prototype方法中,this是字符串對象。 (在嚴格模式下,無論調用什麼方法,通常都是一個字符串原語。)你從console.log看到的不是一個數組,它只是如何輸出一個String對象而不是字符串基元:

console.log(new String("hi"));

有一個在代碼中的錯誤,但:this === "what"將永遠不會在鬆散模式真的,因爲"what"是一個字符串原始,但thisString對象,=== ISN」允許要挾。你想要this.toString() === "what"this == "what"。您可能還想在if附加的塊中執行某些操作。如果你想在返回this時返回一個字符串原語,最後你可能需要return this.toString();

例如,像:

String.prototype.testing = function testing() { 
 
    if (this == "what") { 
 
    return "it was what"; 
 
    } 
 
    return this.toString(); 
 
}; 
 

 
var x = "this is a string"; 
 
var y = x.testing(); 
 
console.log(y); 
 
x = "what"; 
 
y = x.testing(); 
 
console.log(y);

或者使用嚴格模式,像這樣:

"use strict"; 
 
String.prototype.testing = function testing() { 
 
    if (this == "what") { // Could still be either a primitive or object, depending 
 
    return "it was what"; 
 
    } 
 
    return this; // No need for toString here 
 
}; 
 

 
var x = "this is a string"; 
 
var y = x.testing(); 
 
console.log(y); 
 
x = "what"; 
 
y = x.testing(); 
 
console.log(y);

+0

@llama:好,我有一個「啊!」幾分鐘前的那一刻,正在編輯該信息。 –

+0

僅僅是因爲字符串原語是不可變的,不能將方法添加到它上面? – cygorx

+0

@cygorx:不可變並不意味着你不能擁有方法。這是因爲字符串原語是**原語**。基元沒有方法。 *由於JavaScript引擎的特殊處理,它們看起來*:當你在一個基元上調用一個方法(或者在它上面查找任何非內在屬性)時,引擎將這個基元提升爲一個對象,查找屬性/方法,然後(在方法的情況下)用'this'將該方法設置爲基元(嚴格模式)或對象(鬆散模式)。 –

-1

你有...不一個錯誤,但沒有必要增加一個函數名,當你分配給它,在這裏:

String.prototype.testing = function **testing**() {} 

有未必是你的代碼錯誤,但你沒有看到你所期望的:)

佛示例與您擁有的x == x.testing()即使console.log(x)看起來不同於console.log(x.testing())

他們是平等的,但類型不同,其中一個是字符串對象,另一個是字符串原語,正如T.J.在我發帖時很好地解釋了:)。

String.prototype.testing = function() { 
 
     if (this === "what") {} 
 
     return this.toString(); 
 
    } 
 

 

 
    x = "this is a string" 
 

 
    y = x.testing() 
 

 
    console.log(y)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+1

正確的答案,但是你能否給我添加一個解釋? –

+0

@ T.J。 Crowder在下面解釋得非常好:) – bluehipy

相關問題