How to create a primitive wrapper object with prototype

I can wrap a primitive in an object:

> p = Object(1);
< Number {[[PrimitiveValue]]: 1}

      

which allows me to set properties on it:

> p.prop = 2;
> p.prop
< 2

      

still using a primitive object:

> p + 1
< 2

      

I want to decorate such primitive wrapping objects with prototypes. I know that I can set the prototype explicitly with:

> Object.setPrototypeOf(p, { q : 3 });
< Number {prop: 2, q: 3, [[PrimitiveValue]]: 1}

      

Is there a way to create wrapper objects with the prototype already set so I don't have to install it on every newly created wrapper (or pollute the prototype Object

)? Perhaps by creating ObjectWrapper

that would work like this:

> ObjectWrapper = ...???...
> ObjectWrapper.prototype = { q : 3 };
> [new] ObjectWrapper(1)

      

which I would like to give

< Number {q:3, [[PrimitiveValue]]: 1}function

      

+3


source to share


2 answers


You can use this structure ...



//outer function is to provide support for multiple wrappers with different inheritance
function PrimitiveWrapper(){
        return function(x){
            this.valueOf = function(){
                return x;
            }
        };
    };

var wrapper1 = PrimitiveWrapper();
wrapper1.prototype.p = 3;
var w11 = new wrapper1(1);
var w12 = new wrapper1(2);

var wrapper2 = PrimitiveWrapper();
var w21 = new wrapper2(1);

console.log(w11+3); //4
console.log(w11.p); //3
console.log(w12+3); //5
console.log(w12.p); //3

console.log(w21+3); //4
console.log(w21.p); //undefined

      

0


source


Does this work for you? You create ObjectWrapperCreator

which gives you a function back that you can call, for example:



function ObjectWrapperCreator(prototype) {

    var wrapper = function(param) {
        prototype.param = param;
        var obj = Object(param);
        Object.setPrototypeOf(obj, prototype);
        obj.valueOf = function() {
            return this.param;
        };
        return obj;
    };
    return wrapper;
}

Usage:
  var b = ObjectWrapperCreator({p: 1});
  var c = b(4);
  >> c + 1 

      

0


source







All Articles