b2和b3没有触发原型功能,没有产生错误?如何以时尚的方式完成调用原型函数?
<html>
<head>
<script type="text/javascript">
function newObj(){
this.obj_val= 7;
}
var trigger_f0 = function(){
alert("here 0"); // trigger FINE! (ok)
}
newObj.prototype.trigger_f2 = function (){ // no triggering off click event
alert("here 2");
}
newObj.prototype.trigger_f3 = function (){ // not triggering off click event
alert("obj value:" + newObj.obj_val);
}
var init = function(){
b3.addEventListener('click', newObj.trigger_f3, false);
b2.addEventListener('click', newObj.trigger_f2, false);
b1.addEventListener('click', trigger_f0, false);
}
window.addEventListener('DOMContentLoaded', init, false);
</script>
</head>
<body>
<button id="b1">B1</button>
<button id="b2">B2</button>
<button id="b3">B3</button>
</body>
</html>
&#13;
答案 0 :(得分:2)
您需要创建一个实例,以便从构造函数
中获取对象var a=new newObj()
然后访问属性。
并将newObj.obj_val
更改为
new newObj().obj_val
function newObj() {
this.obj_val = 7;
}
var trigger_f0 = function() {
alert("here 0"); // trigger FINE! (ok)
}
newObj.prototype.trigger_f2 = function() { // no triggering off click event
alert("here 2");
}
newObj.prototype.trigger_f3 = function() { // not triggering off click event
alert("obj value:" + new newObj().obj_val);
}
var a = new newObj();
b3.addEventListener('click', a.trigger_f3, false);
b2.addEventListener('click', a.trigger_f2, false);
b1.addEventListener('click', trigger_f0, false);
&#13;
<body>
<button id="b1">B1</button>
<button id="b2">B2</button>
<button id="b3">B3</button>
</body>
&#13;
答案 1 :(得分:0)
创建函数并向其.prototype
添加属性时,该函数不会接收它们。
相反,当您使用该函数作为构造函数创建实例/对象时,该对象将获得函数。
function foo() {}
foo.prototype.fn = function(){}
var x = new foo()
console.log(foo.fn) // undefined
console.log(x.fn) // function (){}
在你的情况下,
// ...
var obj = newObj();
var init = function(){
b3.addEventListener('click', obj.trigger_f3, false);
b2.addEventListener('click', obj.trigger_f2, false);
b1.addEventListener('click', trigger_f0, false);
}
window.addEventListener('DOMContentLoaded', init, false);