开发者

Object.create and private functions in modules

This is a standalone implementation of ES5's Object.create:

window.createObject = (function() {
    var F = function () {};
    return function(o) {
        F.prototype = o;
        return new F();
    }
}());

and an example of its use:

var cat = createObject(animal);

I've noticed the internals of animal are g开发者_如何学Cetting a little messy when trying to call private functions, e.g.:

animal = (function() {
    function privFunc(arg) {
        this.property;
    }

    function publFunc(arg) {
        privFunc.call(this, arg);
    }

    return {
        publFunc: publFunc
    }
}());

Is there a cleaner way to follow this type of pattern? In particular, removing the need for privFunc.call(this, arg).

Another way, equally as ugly is:

function privFunc(animal, arg) {
    animal.property;
}

function publFunc(arg) {
    privFunc(this, arg);
}


Unfortunately this is the only way to combine Object.create and private functions. The new object created only has access to the public methods that the module which defines the prototype has exposed. Using private methods within the module requires passing to those methods the object which you'd like to work with - as either a named parameter, or manipulating the value of this

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜