Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ';这';与原型中的杆不相等_Javascript_Arrays_Object_Callback - Fatal编程技术网

Javascript ';这';与原型中的杆不相等

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

在下面的代码段中,“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 == 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));

如果我是你的话,我会考虑把这些物品传递给工厂,在你试图做的事情上会更有意义。如果我是你的话,我会考虑把这些物品传递给工厂,在你试图做的事情上,我会觉得更有意义。