尝试创建具有一些自定义属性的元素
function x(){
var f=document.createElement("div");
this.name="monkey";
return f;
}
x.prototype.myFunction=function(){
alert(arguments[0]+this.name);
};
var c=new x();
c.myFunction("hello");
浏览器说 c.myFunction 不是函数
尝试创建具有一些自定义属性的元素
function x(){
var f=document.createElement("div");
this.name="monkey";
return f;
}
x.prototype.myFunction=function(){
alert(arguments[0]+this.name);
};
var c=new x();
c.myFunction("hello");
浏览器说 c.myFunction 不是函数
您在函数中返回一个 HTML 元素,因此c将引用该元素而不是您的对象。
删除return f;,您将获得包含“hellomonkey”的警报框的预期输出
这适合你吗?
function x(){
var f=document.createElement("div");
this.name="monkey";
this.myFunction=function(){
alert(arguments[0]+this.name);
};
this.returnDiv = function() {
return f;
}
return this;
}
var c=new x();
c.myFunction("hello");