3

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>

4

2 回答 2

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);
<body>
  <button id="b1">B1</button>
  <button id="b2">B2</button>
  <button id="b3">B3</button>

</body>

于 2017-03-12T20:52:05.700 回答
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);
于 2017-03-13T05:26:24.990 回答