开发者

Creating prototype chains in JavaScript (ES-5)

I'm trying to create a function that creates an object with a prototype chain, like this:

something = object(proto1, proto2, proto3);
// Lookup order is something -> proto1 -> proto2 -> proto3 -> Object.prototype

I'd to wrap the given prototypes to override their own lookup chains (so they can be reused), and want to do so with minimal copying/inner attribute wrapping.

Is there any feature in Javas开发者_如何学编程cript/ECMAScript 5 that can be used to override all attribute accesses on an object? Something akin to __getattribute__(self, attrname) in Python? If not, how should I go about this? Am I forced to just clone the object's properties (with Object.hasOwnProperty())?


JavaScript has prototypes, so could use a construct like:

// Small utility function
function Object.extend(obj, properties) {
    for (var i in properties) {
        obj[i] = properties[i];
    }
    return obj;
}

// Create a subclass of Object 
function Class3() {}
Class3.prototype = proto3;

// Create a subclass of Class3
function Class2() {}
Class2.prototype = new Class3();
Object.extend(Class2.prototype, proto2);

// Create a subclass of Class2
function Class1() {}
Class1.prototype = new Class2();
Object.extend(Class1.prototype, proto1);

// Instantiate an object whose prototype chain is proto1, proto2, proto3
var something = new Class1();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜