Javascript ';这';与原型中的杆不相等
在下面的代码段中,“this.x()”只能在案例2中调用(请参见main())。 同样,Bar在情况1中不相等,但在情况2中相等Javascript ';这';与原型中的杆不相等,javascript,arrays,object,callback,Javascript,Arrays,Object,Callback,在下面的代码段中,“this.x()”只能在案例2中调用(请参见main())。 同样,Bar在情况1中不相等,但在情况2中相等 function Class_Bar() { this.panel = null; this.init = function () { // do some stuff this.panel = 20; } this.apply = function () { alert(Bar == t
function Class_Bar() {
this.panel = null;
this.init = function () {
// do some stuff
this.panel = 20;
}
this.apply = function () {
alert(Bar == this);
Bar.x();
this.x();
}
this.x = function() {
alert("Some friendly message");
alert(Bar.panel);
}
}
var Bar = new Class_Bar();
function Class_Factory() {
this.factories = new Array();
this.add = function (init, apply) {
this.factories.push({"init":init, "apply":apply});
}
this.init = function () {
for (var i = 0; i < this.factories.length; ++i) {
this.factories[i]["init"]();
}
}
this.apply = function () {
for (var i = 0; i < this.factories.length; ++i) {
this.factories[i]["apply"]();
}
}
}
var Factory = new Class_Factory();
function main() {
// Case 1
Factory.add(Bar.init, Bar.apply);
Factory.init();
Factory.apply();
// Case 2
Bar.init();
Bar.apply();
}
main();
函数类_Bar(){
this.panel=null;
this.init=函数(){
//做点什么
该面板=20;
}
this.apply=函数(){
警报(条==此);
Bar.x();
这个.x();
}
this.x=函数(){
警惕(“一些友好的信息”);
警报(条形面板);
}
}
var Bar=新类_Bar();
函数类_工厂(){
this.factories=新数组();
this.add=函数(init,apply){
push({“init”:init,“apply”:apply});
}
this.init=函数(){
对于(var i=0;i
有没有关于如何“修复”/解决此行为的想法
我找到了一个可能的解决方案,但这似乎是一个“坏”黑客行为。通过传递
Bar.init
,您实际上只传递了函数,而不是它所属Bar
的信息(即此
值应该是什么)。您可以做的是绑定该信息:
Factory.add(Bar.init.bind(Bar), Bar.apply.bind(Bar));
通过传递
Bar.init
,实际上只传递了函数,而不是它所属的Bar
信息(即此
值应该是什么)。您可以做的是绑定该信息:
Factory.add(Bar.init.bind(Bar), Bar.apply.bind(Bar));
如果我是你的话,我会考虑把这些物品传递给工厂,在你试图做的事情上会更有意义。如果我是你的话,我会考虑把这些物品传递给工厂,在你试图做的事情上,我会觉得更有意义。