2013-12-10 243 views
0

我試圖給我的函數傳遞一個參數,但它沒有通過。將參數值傳遞給javascript函數

<html> 
    <head> 
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> 
     </script> 
     <script> 
      $(document).ready(function() { 
       function Person() { 
        alert('New Person Created'); 
       } 
       Person.prototype.sayHello = function (parm1) { 
        alert('Hello from = ', parm1); 
       }; 
       var itsme = new Person(); 
       itsme.sayHello('Prem'); 
       var newfunction = itsme.sayHello; 
       newfunction.call(itsme); 
      }); 
     </script> 
    </head> 
    <body> 
    </body> 
</html> 
+0

jQuery是沒用的她即 – leaf

回答

0

這與傳遞參數無關;這是一個語義錯誤的簡單問題。 (您的控制檯不會將其顯示爲語法錯誤,因爲您可以將額外參數傳遞到所有JavaScript函數中。)

alert('Hello from = ', parm1);是問題所在。 alert只需要一個參數,所以使用字符串concatenation。如果您改爲使用alert('Hello from = ' + parm1),則應該看到參數正常運行。

+0

這不是語法錯誤。 'alert'是一個函數,函數可以接受任意數量的參數。 'alert'只是使用參數[0]。它不像'if(arguments.length> 1)拋出新的SyntaxError(「...」)' – C5H8NNaO4

+0

@ C5H8NNaO4嘿,味精。我會堅持語法錯誤,因爲我解釋了爲什麼它不會拋出一個。即使瀏覽器的編譯器沒有捕獲它,它**仍然是'alert'語法中的錯誤。 –

+0

Hey :)不過,[WebAPI規範](http://www.w3.org/TR/html5/webappapis.html#dom-alert)描述的唯一要點是1.如果事件循環的終止嵌套級別不是-zero,可以選擇放棄這些步驟。 2.釋放存儲互斥鎖。 3.或者,終止這些步驟4.向用戶顯示給定的「消息」。 5.可選地,在等待用戶確認消息時暫停。我沒有看到這應該是警報語法中的**錯誤**。 – C5H8NNaO4

2

有兩件事情正在進行。

  • window.alert只顯示第一個參數,其他的都被忽略,
    window.alert(message);
                              ^^^Accepts a single argument
  • 你沒有隻傳遞一個thisValueFunction.prototype.call。你需要傳遞一個字符串作爲第二個參數。
    fun.call(thisArg[, arg1[, arg2[, ...]]])
                                      ^^^ The string passed to sayHello

function Person() { 
    alert('New Person Created'); 
} 
Person.prototype.sayHello = function (parm1) { 
    alert('Hello from = ' + parm1); 
    //     ^^^ You should pass a single argument to alert, you can concatenate strings with a + 
}; 

var itsme = new Person(); 
itsme.sayHello('Prem'); 
var newfunction = itsme.sayHello; 
newfunction.call(itsme, "new function"); 
//       ^^^ You weren't actually passing any parameter 
+0

+1用於捕獲我錯過的'call'錯誤。 –