简体   繁体   English

javascript对象原型调用

[英]javascript object prototype call

b2 and b3 are not triggering the prototype functions and no errors are generated? b2和b3没有触发原型功能,没有产生错误? How does one accomplish calling prototype functions in the fashion? 如何以时尚方式完成调用原型函数?

 <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> 

You need to create an instance like to get an object out of the constructor function 您需要创建一个实例,以便从构造函数中获取对象

var a=new newObj()

and then access the properties. 然后访问属性。 and change newObj.obj_val to 并将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> 

When you create a function and add properties to its .prototype , the function doesn't receive them. 当您创建函数并向其.prototype添加属性时,该函数不会接收它们。

Instead, when you create an instance/object using that function as constructor, that object will get the functions. 相反,当您使用该函数作为构造函数创建实例/对象时,该对象将获得函数。

function foo() {}
foo.prototype.fn = function(){}

var x = new foo()

console.log(foo.fn) // undefined
console.log(x.fn)   // function (){}

In your case, 在你的情况下,

// ...

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM