Javascript:Prototype对象不是函数
希望有人能帮我写下这段代码 JavaScript:Javascript:Prototype对象不是函数,javascript,function,object,prototype,Javascript,Function,Object,Prototype,希望有人能帮我写下这段代码 JavaScript: function myFrame(id){ if (id) { if (window === this) { return new myFrame(id); } this.e = document.getElementById(id); return this; } else { return ""; } } myFrame.prototype
function myFrame(id){
if (id) {
if (window === this) {
return new myFrame(id);
}
this.e = document.getElementById(id);
return this;
} else {
return "";
}
}
myFrame.prototype = {
math: function () {
alert(1 + 1);
},
hide: function () {
this.e.style.display = 'none';
return this;
}
}
<p id="hideParagraph">Hide Paragraph</p>
<input type="button" name="math" onclick="hide()" value="Hide Paragraph" />
<input type="button" name="math" onclick="math()" value="Alert Math" />
<script type="text/javascript">
function math() {
myFrame("body").math();
}
function hide() {
myFrame("hideParagraph").hide();
}
</script>
HTML:
function myFrame(id){
if (id) {
if (window === this) {
return new myFrame(id);
}
this.e = document.getElementById(id);
return this;
} else {
return "";
}
}
myFrame.prototype = {
math: function () {
alert(1 + 1);
},
hide: function () {
this.e.style.display = 'none';
return this;
}
}
<p id="hideParagraph">Hide Paragraph</p>
<input type="button" name="math" onclick="hide()" value="Hide Paragraph" />
<input type="button" name="math" onclick="math()" value="Alert Math" />
<script type="text/javascript">
function math() {
myFrame("body").math();
}
function hide() {
myFrame("hideParagraph").hide();
}
</script>
有没有一种方法可以让我拥有这样的代码:
myFrame().math();
并且仍然使用“隐藏”方法,如:
myFrame("hideParagraph").hide();
非常感谢您的帮助 问题在于你的
return "";
尝试:
也许这会帮助您了解您的问题:
function Thing(val) {
this.val = val;
};
Thing.prototype.alert = function() {
alert(this.val);
};
function start(val) {
return new Thing(val);
}
start("Hi").alert();
您需要一个具有alert方法的类,然后在外部函数中创建该类的新实例
可能有很多方法可以做到这一点。使用此设置,您可以多次调用
start
。这里的问题是您的返回值
调用myFrame(“body”)
时,函数中的窗口===this
为true
,因此调用新的myrFrame(“body”)
。当这种情况发生时,您将返回此值代码>。新创建的对象。这个对象在其原型上包含.math()
和.hide()
方法
myFrame().math()代码>另一方面myFrame()
使if(id)
检查失败,因此它只返回'
。空白字符串。不是myFrame()
对象。字符串没有.math()
方法
您需要调整myFrame
函数,如下所示:
function myFrame(id){
// Determine whether we called 'myFrame()` or 'new myFrame()'
// In "use strict"; (strict mode), do `if(!this)`
if (window === this) {
return new myFrame(id);
}
else{
// In here, this is our new myFrame object
if(id){
this.e = document.getElementById(id);
}
// This return statement isn't actually needed
// return this;
}
}
确保它始终返回一个对象,而不管您传递的参数是什么。您专门编写了代码,使其无法工作。如果math
函数不需要元素的上下文,为什么它甚至在原型上?要么使其myFrame.math=function
或将其完全分离。return”“代码>。调用myFrame()
时,返回的是一个空字符串(不是新的myFrame
对象)。字符串没有.math()
方法。请关闭,但不完全关闭。如果他做了myFrame()
,然后返回这个
,他会得到窗口
,因为您在任何上下文中都没有调用myFrame()
。要使其工作,您需要执行newmyframe()
,并让它返回新创建的对象。