0
在下面的代码中,当单击该按钮时出现错误:TypeError: i.Print is not a function
。这个错误的原因是什么,我该如何解决?当我查看按钮的click
处理程序中的i
的值时,使用Firefox调试器,我看到i.prototype.Print
的值为Outer/Inner.prototype.Print()
。如何解决函数原型上的'不是函数'错误?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<p id="prn">Value here</p>
<button id='btn'>Print</button>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
</script>
<script>
function TestObject(i)
{
$("#btn").on("click", function() {
i.Print();
i.Change(Math.random() * 10 + 5);
});
}
function TestPrototype()
{
var o = function Outer() {
function Inner(v)
{
var iv = v;
function print()
{
$("#prn").text(iv);
}
};
Inner.prototype.Print = function() {
print();
console.log(iv);
};
Inner.prototype.Change = function(nv) {
iv = nv;
};
return {
getInner : function(v) {
var i = Inner;
i(v);
return i;
}
};
}();
var i1 = o.getInner(10);
TestObject(i1);
}
;(function() {
TestPrototype();
}());
</script>
</body>
</html>
这解决了问题。但是现在,'Inner'对象的私有方法'print'和成员变量'iv'不能从它的'Print'方法访问。 –
我编辑了我的答案,使用成员变量可以解决这个问题。您可以在日志中看到输出。即_console.log_ –
是的,工作。因此对'prototype'函数的需求是可用的,即对象应该使用'new'关键字创建? –