为什么点击图片时不调用原型(prototype)函数?
HTML 代码:--
<!DOCTYPE html>
<html style="height: 100%;">
<head>
<script type="text/javascript" src="tt.js"></script>
</head>
<body>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<input type="image" src="http://t2.gstatic.com/images?q=tbn:ANd9GcSTcJA5J-LOj0HOP1ZMzdSQIsxwuguFdtlesHqzU15W8TXx232pFg" onclick="myFunction('Info clicked')"/>
<script>
var a = new myFunction();
document.getElementById("demo").innerHTML = a.k;
</script>
</body>
</html>
Java 脚本:--
function myFunction(l) {
this.k = "hello";
alert(this.k);
var t = this.temp(l);
alert(t);
}
myFunction.prototype.temp = function(a)
{
alert(a);
return 10;
}
如果我将 html 页面主体放入其中,它会起作用:--
<script>
var a = new myFunction();
document.getElementById("demo").innerHTML = a.k;
</script>
最佳答案
因为您是在构造函数上调用 this.temp()
而不是在它的实例上。
您需要使用new
创建一个实例。
new myFunction('Info clicked')
请注意,这没有意义。如果你想在构造函数运行时做一些事情,你应该将方法分配给构造函数而不是原型(prototype)。
关于javascript函数对象原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25306079/