在以下代码中,单击按钮时出现错误:TypeError: i.Print is not a function
。导致此错误的原因是什么,我该如何解决?当我在按钮的i
处理程序中查看click
的值时使用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>
答案 0 :(得分:2)
您需要使用构造函数
创建对象
<!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)
{
// instatiate member variables
this.iv = v;
this.print = print;
function print()
{
$("#prn").text(this.iv);
}
};
Inner.prototype.Print = function() {
// access member variable
console.log(this.iv);
this.print();
print();
};
Inner.prototype.Change = function(nv){
iv = nv;
};
return {
getInner : function(v) {
var i = Inner;
return new i(v);
}
};
}();
var i1 = o.getInner(10);
TestObject(i1);
}
;(function() {
TestPrototype();
}());
</script>
</body>
</html>