2011-11-30 16 views
7

私は(おそらくそれの私のブラウザの考えをか)JavaScriptでクセを発見:文字列が `this`になると文字列が切り取られるのはなぜですか?

var s = "Hello, world"; 

function foo(arg) 
{ 
    console.log(arg); 
    console.log(this); 
} 

foo.call(s, s); 

Firebugのコンソールで上記を実行している私が手に、有効:

Hello, world 
String { 0="H", 1="e", more...} 

はなぜ文字列が自動的に点灯取得ん奇妙なオブジェクトになる前にに渡されるthis

私が奇妙なオブジェクトと呼んでいるのは、jQueryがそれを嫌うからです。 thisはちょうどオブジェクト(私は文字列がオブジェクトである知っているが、彼らはまた、文字列である)であるため、

$.each(["one", "two", "three"], function(i, x) { 
    $('<p></p>').text(x) .appendTo('body'); // Works 
    $('<p></p>').text(this).appendTo('body'); // Doesn't work 
}); 
+0

さて、 'this'は' window'を参照してください。 機能。 – mc10

+0

面白い振る舞い。間違った数の引数を渡すことに関連していると仮定します。 argsの数が変わる場合は、argumentsオブジェクトを使用します。 –

答えて

4

thisすなわちObject("test")が内部的に呼び出され、オブジェクトに強制されます。

(function() { 
    return this; 
}).call("test"); 

// returns same as `new String("test")` or `Object("test")` 

if the method is a function in non-strict mode ... primitive values will be boxed*.

確かstrictモードを使用すると、プリミティブ値を返すんのでご注意:

(function() { 
    "use strict"; 
    return this; 
}).call("test") === "test"; // true 

* Boxing a value of a value allocates an object instance and copies the value into the new object.

foo.call(s1, s2)を使用する場合は
1

は:たとえば

var s = "Hello, world"; 

function foo(arg) 
{ 
    console.log(typeof arg); // string 
    console.log(typeof this); // object 
} 

foo.call(s, s); 
1

、あなたは機能fooを起動し、s1thisキーワードを設定しています。 thisはオブジェクトでなければならないため(プリミティブ値ではないため)、Stringオブジェクトに変換されます。 (s = "..."又はs = String("...")介して作成された)文字列の個々の文字は、インデックスを介してアクセスすることができる

、したがって

String { 0="H", 1="e", more...} 

function foo(arg) 
{ 
    console.log(arg); // passed as "Hello, world" 
    console.log(this); // passed as String("Hello, world") 
    console.log(this instanceof String); //True 
} 


インデックスを実証するコード:

var i=0, s = "Hello, world"; 
for(; i<s.length; i++){ 
    console.log(i, s[i]); 
} 
/* Prints: 
    0 H 
    1 e 
    ... 
    */ 
*/