如何在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;
};