[英]Passing parameter value to javascript function
我正在尝试将参数传递给我的函数,但它没有被传递。
<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>
有两件事情在发生。
window.alert
只显示第一个参数,其他参数被忽略 window.alert(message);
^^^Accepts a single argument
thisValue
传递给Function.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
这与传递参数无关; 这是一个简单的问题,即出现语义错误。 (您的控制台没有将其显示为语法错误,因为您可以将额外的参数传递给所有JavaScript函数。)
alert('Hello from = ', parm1);
是问题。 alert
只接受一个参数,因此请使用字符串连接。 如果您改为使用alert('Hello from = ' + parm1)
,您应该看到参数正常运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.