Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/70.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_Jquery - Fatal编程技术网

如何在javascript中将对象转换为函数

如何在javascript中将对象转换为函数,javascript,jquery,Javascript,Jquery,如何将对象转换为函数 var FRUIT = {}; FRUIT.color={ name: "", foo: function(){ return this.name; }, yellow: { yellow1: 0, yellow2: 0 } }; var castFunction = function(){}; $.each( FRUIT.color, function(i, prop){ c

如何将对象转换为函数

var FRUIT = {};
FRUIT.color={
    name: "",
    foo: function(){
        return this.name;
    },
    yellow: {
        yellow1: 0,
        yellow2: 0
    }
};

var castFunction = function(){};
$.each( FRUIT.color, function(i, prop){
    castFunction.prototype[i] = prop;
});

var classSmall = new castFunction();
var classBig = new castFunction();

classSmall.name="Yellow small Fruit";
classBig.name="Yellow big Fruit";

classSmall.yellow.yellow1=100;
classBig.yellow.yellow1=10000;

console.log( classSmall.foo() );//Yellow small Fruit ==> OK
console.log( classBig.foo() );//Yellow big Fruit ==> OK
console.log( classSmall.yellow.yellow1 );//10000 ==> why
我把它定为100而不是10000 为什么第一类值可以从第二类值更改

实际上,如果我使用该函数,上面的问题不是问题,但我只是想知道上面的错误在哪里,或者确实无法解决。

试试这种方法

var A = function(foo) {                                                                                                      
    var B = function() {                                                                                                       
        return A.prototype.constructor.apply(B, arguments);
      };
      B.prototype = A.prototype;                                                                                                 
      return B;                                                                                                                  
    };