Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So I created a function like this,

var functionName = function(arg1) { //code logic here; }

At the same time, I need this function to work as an object. It will not really save anything, but the data will be accessed from another object.

var myObj = new Object();
myObj.x = 3;
myObj.y = 4;

So when I go, functionName.x it should return myObj.x. The myObj object is being maintained someplace else and I don't have any control of it.

This is how I currently implemented it,

functionName.__proto__ = myObj;

It works fine. But __proto__ is deprecated already and I would want to see if there is any other safe way of doing it. I thought of overriding Function.prototype but it doesn't work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
838 views
Welcome To Ask or Share your Answers For Others

1 Answer

You want to implement a delegate to myObj:

     var functionName = function(arg1) { // code }

     functionName.myObj = new MyObj();
     for (prop in functionName.myObj) {
       if (functionName.myObj.hasOwnProperty(prop)) {
         functionName.__defineGetter__(prop, function() { return functionName.myObj[prop]; } );
       }
     }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...