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

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

create function in javascript with custom prototype

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

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

1 Answer

0 votes
by (71.8m points)

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]; } );
       }
     }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...