Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 258
John Ng Avatar asked Nov 13 '22 22:11

John Ng


2 Answers

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]; } );
       }
     }
like image 96
Tanzeeb Khalili Avatar answered Nov 15 '22 11:11

Tanzeeb Khalili


I am having the same problem here. Unfortunately, there is no good solution under EcmaScript 5.1.

In the language specification http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf it says in 13.2 "Creating Function Objects" that the [[Prototype]] internal property of a newly created function object is always the standard built-in Function prototype object.

As detailed in 13.3 of the same specification, using the Function constructor is also of no help as a function constructed by new Function(…) also uses the method detailed in 13.2. (This is reflected by the fact that the prototype property of Function is neither writable nor configurable.

So to achieve what you want, you need a method to change the prototype of already existing objects. Fortunately, the upcoming Ecmascript 6 standard seems to standardises Object.prototype.__proto__ as per annex B.2.2 in the recent draft http://wiki.ecmascript.org/lib/exe/fetch.php?id=harmony%3Aspecification_drafts&cache=cache&media=harmony:working_draft_ecma-262_edition_6_05-14-13-nomarkup.pdf.

like image 21
Marc Avatar answered Nov 15 '22 10:11

Marc