b2 和 b3 没有触发原型(prototype)函数,也没有产生错误?如何实现调用原型(prototype)函数的方式?
<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>
最佳答案
您需要创建一个实例,例如从构造函数中获取对象
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);
<body>
<button id="b1">B1</button>
<button id="b2">B2</button>
<button id="b3">B3</button>
</body>
关于javascript对象原型(prototype)调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42752875/