2015-03-19 127 views
1

我希望能夠創建一個類似於傳遞給它的對象的類,並向此對象添加新方法。oop行爲類似構造函數參數類型的類

這裏是我到目前爲止有:

Node = function(data) { 
    Node = data; 
    Node.constructor.prototype = new data.constructor(); 
    Node.constructor.prototype.testProp = "Hello!"; 
    return Node; 
}; 

node = Node('abc'); 
console.log(node); // abc 
console.log(node.testProp); // Hello! 
var testArray = []; 
testArray.push(node); 
console.log(testArray); // ['abc'] 

請告訴我這個實現的問題?

在本示例中,Node類看起來像一個String,但每個字符串現在都有一個testProp屬性。

console.log(node.testProp) // 'Hello!' 
console.log("something".testProp) // 'Hello!' 

我的問題:

我多麼應該實現一個類,會表現得像這是傳入構造不會影響同一類的其他對象的對象?

爲什麼?

爲什麼我問這個的原因是我想要的元素數據(字符串,數字,數組,對象等)是不使用例如console.log(Node.value);任何方法或道具訪問,相反,我只是想使用console.log(Node);

謝謝!

+2

那麼,在你的榜樣,你傳遞一個*原始*值,而不是對象。在不影響相同類型的所有基元的情況下,不能「擴展」原始值。如果你使用實際的對象,你可能只是想直接給它分配新的屬性,而不是它的原型。但我想我並不真正瞭解「看起來像對象的類」是什麼意思。你想動態創建子類嗎? – 2015-03-19 00:14:36

+0

@FelixKling感謝Felix的澄清,你會看到任何解決方法,這將使原始值的實現成爲可能嗎? – 2015-03-19 00:22:12

+0

@FelixKling我想要的是能夠console.log(節點)和輸出爲一個字符串爲例,並且相同的行爲在一個數組中。 – 2015-03-19 00:23:28

回答

3

getter和setter on global

此解決方案不需要「。」但它只適用於全局變量。

var test = {value: "Hello World!"}; 

Object.defineProperty(window,'node_a', { 
    get: function() {return test.value;}, 
    set: function(newValue) {test.value = newValue;}, 
    enumerable: true, 
    configurable: true 
}); 

function nodeValue() { 
    console.log(node_a); 
    node_a = "Foo Bar"; 
    console.log('test.value=' + test.value); 
    console.log(node_a); 
} 

nodeValue(); 

輸出:

Hello World! 
test.value=Foo Bar 
Foo Bar 

的toString和的valueOf

您可以通過創建的toString和功能的valueOf你的對象轉換爲字符串或數字。這會讓你關閉,但是當它沒有被字符串處理時,我們仍然會對該值進行序列化。

function Node(data) { 
    this.data = data; 
    this.test = 'world!'; 
} 

Node.prototype.toString = function() { 
    return this.data; 
}; 

Node.prototype.valueOf = function() { 
    return this.data; 
} 

var n = new Node('Hello'); 

console.log(n); 
console.log(n+""); 
console.log(n.test); 

輸出

Node { data="Hello", test="world!", toString=function(), more...} 
Hello 
world! 
+0

感謝您的幫助,但我希望能夠使用console.log(n)來做到這一點。 – 2015-03-25 18:35:04

+0

這看起來像我發佈的示例:http://gist.github.com/NV/282770 – 2015-03-25 18:35:56

+0

你知道如何在Node.js中做到這一點? – 2015-03-30 22:28:32

3

下不與基本類型(如字符串和數字),但工作可與對象:

node = function(data) {//do not capitalize non constructor functions 
    ret = Object.create(data); 
    ret.testProp = "Hello!"; 
    return ret; 
}; 

var proto = {name:'hello'}; 
test = node(proto); 
console.log(test); //{testProp: "Hello!", name: "hello"} 
console.log(test.testProp); // Hello! 

請注意,如果發生變異原你變異測試:

proto.name='changed'; 
console.log(test);//{testProp: "Hello!", name: "change"}