2014-05-06 24 views
-1

到功能如何將對象轉換成一個函數如何轉換對象的JavaScript

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多萬 爲什麼頭等艙值可以從第二類被改變。

實際上,如果我使用這個函數,上面的問題並不是問題,但我只是想知道上面的錯誤或者確實無法完成的地方。

回答

1

嘗試這種方式

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