2015-03-19 121 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"}