creating non existing method on an object in javascript - javascript

How do getter or setter works on object in javascript ?
i.e.
In python if I call a nonexistent method on an object I could intercept the call via getter and setter and in turn return from getter and setter.
How do I do similar functionality in JavaScript ?
https://github.com/Flotype/now/blob/master/lib/client/now.js implements this functionality somehow. I didn't understand the trick. can anyone explain ?

Creating the same functionality is virtually impossible in Javascript. My best guess would be something like this:
var getter = function (propName) {
if (propName in this) {
return this[propName];
} else {
return "no prop";
}
};
You can call this function on any object you like using this syntax:
a = { "test": "yes" };
b = {}
console.log(getter.call(a, "test"));
console.log(getter.call(b, "test"));
It's not the best solution but I don't think there's a better way.

1) You can use non-standart mozilla __noSuchMethod__ property.
2) EcmaScript 6 Harmony propose the Proxy object. See Simulating __noSuchMethod__

Related

javascript: prototype in javascript like reflection in c#, is it possible? [duplicate]

In Ruby I think you can call a method that hasn't been defined and yet capture the name of the method called and do processing of this method at runtime.
Can Javascript do the same kind of thing ?
method_missing does not fit well with JavaScript for the same reason it does not exist in Python: in both languages, methods are just attributes that happen to be functions; and objects often have public attributes that are not callable. Contrast with Ruby, where the public interface of an object is 100% methods.
What is needed in JavaScript is a hook to catch access to missing attributes, whether they are methods or not. Python has it: see the __getattr__ special method.
The __noSuchMethod__ proposal by Mozilla introduced yet another inconsistency in a language riddled with them.
The way forward for JavaScript is the Proxy mechanism (also in ECMAscript Harmony), which is closer to the Python protocol for customizing attribute access than to Ruby's method_missing.
The ruby feature that you are explaining is called "method_missing" http://rubylearning.com/satishtalim/ruby_method_missing.htm.
It's a brand new feature that is present only in some browsers like Firefox (in the spider monkey Javascript engine). In SpiderMonkey it's called "__noSuchMethod__" https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/NoSuchMethod
Please read this article from Yehuda Katz http://yehudakatz.com/2008/08/18/method_missing-in-javascript/ for more details about the upcoming implementation.
Not at the moment, no. There is a proposal for ECMAScript Harmony, called proxies, which implements a similar (actually, much more powerful) feature, but ECMAScript Harmony isn't out yet and probably won't be for a couple of years.
You can use the Proxy class.
var myObj = {
someAttr: 'foo'
};
var p = new Proxy(myObj, {
get: function (target, methodOrAttributeName) {
// target is the first argument passed into new Proxy, aka. target is myObj
// First give the target a chance to handle it
if (Object.keys(target).indexOf(methodOrAttributeName) !== -1) {
return target[methodOrAttributeName];
}
// If the target did not have the method/attribute return whatever we want
// Explicitly handle certain cases
if (methodOrAttributeName === 'specialPants') {
return 'trousers';
}
// return our generic method_missing function
return function () {
// Use the special "arguments" object to access a variable number arguments
return 'For show, myObj.someAttr="' + target.someAttr + '" and "'
+ methodOrAttributeName + '" called with: ['
+ Array.prototype.slice.call(arguments).join(',') + ']';
}
}
});
console.log(p.specialPants);
// outputs: trousers
console.log(p.unknownMethod('hi', 'bye', 'ok'));
// outputs:
// For show, myObj.someAttr="foo" and "unknownMethod" called with: [hi,bye,ok]
About
You would use p in place of myObj.
You should be careful with get because it intercepts all attribute requests of p. So, p.specialPants() would result in an error because specialPants returns a string and not a function.
What's really going on with unknownMethod is equivalent to the following:
var unk = p.unkownMethod;
unk('hi', 'bye', 'ok');
This works because functions are objects in javascript.
Bonus
If you know the number of arguments you expect, you can declare them as normal in the returned function.
eg:
...
get: function (target, name) {
return function(expectedArg1, expectedArg2) {
...
I've created a library for javascript that let you use method_missing in javascript: https://github.com/ramadis/unmiss
It uses ES6 Proxies to work. Here is an example using ES6 Class inheritance. However you can also use decorators to achieve the same results.
import { MethodMissingClass } from 'unmiss'
class Example extends MethodMissingClass {
methodMissing(name, ...args) {
console.log(`Method ${name} was called with arguments: ${args.join(' ')}`);
}
}
const instance = new Example;
instance.what('is', 'this');
> Method what was called with arguments: is this
No, there is no metaprogramming capability in javascript directly analogous to ruby's method_missing hook. The interpreter simply raises an Error which the calling code can catch but cannot be detected by the object being accessed. There are some answers here about defining functions at run time, but that's not the same thing. You can do lots of metaprogramming, changing specific instances of objects, defining functions, doing functional things like memoizing and decorators. But there's no dynamic metaprogramming of missing functions as there is in ruby or python.
I came to this question because I was looking for a way to fall through to another object if the method wasn't present on the first object. It's not quite as flexible as what your asking - for instance if a method is missing from both then it will fail.
I was thinking of doing this for a little library I've got that helps configure extjs objects in a way that also makes them more testable. I had seperate calls to actually get hold of the objects for interaction and thought this might be a nice way of sticking those calls together by effectively returning an augmented type
I can think of two ways of doing this:
Prototypes
You can do this using prototypes - as stuff falls through to the prototype if it isn't on the actual object. It seems like this wouldn't work if the set of functions you want drop through to use the this keyword - obviously your object wont know or care about stuff that the other one knows about.
If its all your own code and you aren't using this and constructors ... which is a good idea for lots of reasons then you can do it like this:
var makeHorse = function () {
var neigh = "neigh";
return {
doTheNoise: function () {
return neigh + " is all im saying"
},
setNeigh: function (newNoise) {
neigh = newNoise;
}
}
};
var createSomething = function (fallThrough) {
var constructor = function () {};
constructor.prototype = fallThrough;
var instance = new constructor();
instance.someMethod = function () {
console.log("aaaaa");
};
instance.callTheOther = function () {
var theNoise = instance.doTheNoise();
console.log(theNoise);
};
return instance;
};
var firstHorse = makeHorse();
var secondHorse = makeHorse();
secondHorse.setNeigh("mooo");
var firstWrapper = createSomething(firstHorse);
var secondWrapper = createSomething(secondHorse);
var nothingWrapper = createSomething();
firstWrapper.someMethod();
firstWrapper.callTheOther();
console.log(firstWrapper.doTheNoise());
secondWrapper.someMethod();
secondWrapper.callTheOther();
console.log(secondWrapper.doTheNoise());
nothingWrapper.someMethod();
//this call fails as we dont have this method on the fall through object (which is undefined)
console.log(nothingWrapper.doTheNoise());
This doesn't work for my use case as the extjs guys have not only mistakenly used 'this' they've also built a whole crazy classical inheritance type system on the principal of using prototypes and 'this'.
This is actually the first time I've used prototypes/constructors and I was slightly baffled that you can't just set the prototype - you also have to use a constructor. There is a magic field in objects (at least in firefox) call __proto which is basically the real prototype. it seems the actual prototype field is only used at construction time... how confusing!
Copying methods
This method is probably more expensive but seems more elegant to me and will also work on code that is using this (eg so you can use it to wrap library objects). It will also work on stuff written using the functional/closure style aswell - I've just illustrated it with this/constructors to show it works with stuff like that.
Here's the mods:
//this is now a constructor
var MakeHorse = function () {
this.neigh = "neigh";
};
MakeHorse.prototype.doTheNoise = function () {
return this.neigh + " is all im saying"
};
MakeHorse.prototype.setNeigh = function (newNoise) {
this.neigh = newNoise;
};
var createSomething = function (fallThrough) {
var instance = {
someMethod : function () {
console.log("aaaaa");
},
callTheOther : function () {
//note this has had to change to directly call the fallThrough object
var theNoise = fallThrough.doTheNoise();
console.log(theNoise);
}
};
//copy stuff over but not if it already exists
for (var propertyName in fallThrough)
if (!instance.hasOwnProperty(propertyName))
instance[propertyName] = fallThrough[propertyName];
return instance;
};
var firstHorse = new MakeHorse();
var secondHorse = new MakeHorse();
secondHorse.setNeigh("mooo");
var firstWrapper = createSomething(firstHorse);
var secondWrapper = createSomething(secondHorse);
var nothingWrapper = createSomething();
firstWrapper.someMethod();
firstWrapper.callTheOther();
console.log(firstWrapper.doTheNoise());
secondWrapper.someMethod();
secondWrapper.callTheOther();
console.log(secondWrapper.doTheNoise());
nothingWrapper.someMethod();
//this call fails as we dont have this method on the fall through object (which is undefined)
console.log(nothingWrapper.doTheNoise());
I was actually anticipating having to use bind in there somewhere but it appears not to be necessary.
Not to my knowledge, but you can simulate it by initializing the function to null at first and then replacing the implementation later.
var foo = null;
var bar = function() { alert(foo()); } // Appear to use foo before definition
// ...
foo = function() { return "ABC"; } /* Define the function */
bar(); /* Alert box pops up with "ABC" */
This trick is similar to a C# trick for implementing recursive lambdas, as described here.
The only downside is that if you do use foo before it's defined, you'll get an error for trying to call null as though it were a function, rather than a more descriptive error message. But you would expect to get some error message for using a function before it's defined.

Javascript, convenience method for calling super class method from overwritten method

In order to emulate classical, Java-like classes in JavaScript I have a function called
"createClass":
It has 3 arguments:
* Name and path of the constructor function, that should be created.
* Path of the superclass.
* JavaScript object with methods of the class.
For example:
myApp.createClass("myapp.core.JString", "myapp.core.BaseString", {
abc: function () {
...
First I create a constructor function
Cf = function () {
...
If there is a super class ("Base" is the constructor function of the super class):
protoObj = new Base();
protoObj.constructor = Cf;
Now, method by method of the new class, I put them on to the protoObj:
("protos" is the object with the "class" methods)
for (name in protos) {
????????????????????
protoObj[name] = protos[name]
But before putting the methods to the protoObj, I want to create convenience methods for
calling superclass methods from overwritten methods:
init: function () {
this.jstring_super_init();
...
So, where the question marks are, I want to place the following code:
(classnameLast in this case is "jstring" => last part of class path => lowercase)
if ((typeof protos[name] === "function") &&
(protoObj[name]) &&
(typeof protoObj[name] === "function")) {
supername = classnameLast + "_super_" + name;
protoObj[supername] = XXXXXXXXXXXXX
In the place, where the multiple X are, I tried several things, but nothing worked. It should call the method of the overwritten superclass.
Many thanks in advance for your help
Maybe you could do something like this:
for (name in protos) {
var super_function = ...; //wherever it comes from
protoObj[name] = protos[name];
protos[name]._super = super_function;
}
Then, from within the function, you should have access to the super function via this._super. You can even do this._super.call(this, ...) to ensure that the super function is called in the context of this.
Hopefully I'm understanding you correctly. Also, if I can make a suggestion, there might be an easier way to handle classical objects and inheritance. If you don't want to use Typescript, at least try the inheritance model that they use (which is quite common).
http://pastebin.com/Z2kaXqEv
EDIT: What helped me was using the Typescript playground (http://www.typescriptlang.org/Playground/). Play around with it and the class features it has, and see how it compiles to Javascript. That'll help you better understand exactly how you can accomplish classical inheritance in Javascript.
I tried this for XXXXXXXXXXXX, and it worked:
(function(name1, Base1){
return function() {
Base1.prototype[name1].apply(this, arguments);
};
})(name, Base);
I debugged a "jstring_super_init" function call in Firefox 19, Firebug 1.11.2.
Firebug behaved very strangely, jumping to wrong places of the code!!
Then, I inserted "console.log(this.cid);" after the superinit-call.
The cid, which is placed on to "this" in the init method of the super class, was there!!
When debugging with Google Chrome Version 25, it jumps to the right function!

Generating generic getters and setter on javascript object

It is possible to create getters and setters in javascript as shown by
Object.defineProperty
__define***__
In all those instances, the name of the property is known.
Is it possible create a generic one.
By this I mean, I have a getter and or setter and it is called irrespective of the property name.
Is this possible?
If so, how?
regards.
Note:
I did find these after posting the question. Looks like it is currently not possible as the first answer stated.
Is it possible to implement dynamic getters/setters in JavaScript?
Monitor All JavaScript Object Properties (magic getters and setters)
To all time travelers like me:
It was not possible at the time the question was asked, but it is already possible in present versions of EcmaScript via so-called proxy objects. See more here:
Is it possible to implement dynamic getters/setters in JavaScript?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
There is a non standard function __noSuchMethod__() which is executed when a non existing property is invoked as a function.
But I don't think there is exactly what you are looking for in JavaScript (yet).
Not possible in standard javascript at this point.
I suppose you are expected to handle this yourself:
if (!object.hasOwnProperty('foo')) {
// object has a foo property, its value might be undefined
} else if (typeof object.foo != 'undefined') {
// there is a foo property elsewhere on object's prototye chain with
// a value other than undefined
} else {
// the foo property might exist on the prototype chain with
// a value of undefined, or might not exist on the chain at all
}
I feel like you guys were looking for something like this
function getterSetter()
{
var valA;
this.set=function (propName,val)
{
if(typeof this[propName] =='function' )
{
return false;
}
this[propName]=val;
}
this.get=function (propName,val)
{
if(typeof this[propName] =='function' )
{
return false;
}
return this[propName];
}
}
Here the set and get methods are setter and getter. You can verify this with following code.
var testObj=new getterSetter();
testObj.set('valA',10);
alert(testObj.get('valA'));
Also, checking for the propName to set/get is not a function.

Hide method from enumeration

I want to add a method to every object.
When I just set Object.prototype.somefunction = ..., it will come up when somebody enumerates the object using the usual pattern:
for (i in o){
if (o.hasOwnProperty(i)){
// do something with object
}
}
I tried to set it higher up the prototype chain, but that is not possible (at least not possible in Chrome):
TypeError: Cannot set property 'blah' of undefined
Can I set some flag or something on the method so that it won't get enumerated, just like the native methods won't? (Or at least make hasOwnProperty() return false.)
Update: Sorry, I didn't look at it properly. I am using the ExtJS Framework and the object I was looking at had been processed by Ext.apply() which does the following:
for(var p in c){
o[p] = c[p];
}
That's where the "own property" flag gets lost.
So I guess I have no chance (in ECMAScript < 5) to inject a method into all objects that behaves like a native one?
I'm not sure I understand correctly. hasOwnProperty is needed exactly for this case, and enumerating an object via
for (i in o){
if (o.hasOwnProperty(i)){
// do something with object
}
}
should not include methods from Object.prototype. Can you please make a working example where you see this behaviour?
I also do not understand what you mean by
I tried to set it higher up the
prototype chain
as Object.prototype is the root of the chain, so you cannot get any higher.
In short, the solution is doing exactly what you claim you have done. If this does not work, probably you have made a mistake or found a bug.
I'm not sure what you mean. If a method/property is attached to the prototype, hasOwnProperty will return false. See this code:
function Con(){this.enumerableProp = true;};
Con.prototype.fun = function(){return 'that\'s funny'};
var fun = new Con;
alert(fun.hasOwnProperty('fun')); //=> false
alert(fun.hasOwnProperty('enumerableProp')); //=> true
So, what do you mean?
Make a base class and make all other classes extend it. Add the method to the base class.
ES5 has Object.getOwnPropertyNames() for this:
Object.prototype.lolwat = 42;
var obj = {
'foo': 1,
'bar': 2
};
Object.getOwnPropertyNames(obj); // ['bar', 'foo']
To see where it is supported: http://kangax.github.com/es5-compat-table/
However, for-in combined with a hasOwnProperty check should work too.
You get that error because there is nothing higher up the prototype chain.
Of note also is that adding to Object's prototype is not really recommended unless absolutely necessary for some reason
Edit: actually, my original answer was incorrect - as the others have pointed out, your object should not have that as own property if it's in Object's prototype.
In any case, if you want to create a prototype chain (or more importantly, avoid changing Object's prototype), you'll want to create your own class:
function MyBaseClass(){
}
MyBaseClass.prototype = new Object();
MyBaseClass.prototype.someMethod = function() { /* your method */ };
var o = new MyBaseClass();
o.hasOwnProperty('someMethod') //should be false

Is there a method I can overload to handle undefined properties in JavaScript? [duplicate]

This question already has answers here:
Is there an equivalent of the __noSuchMethod__ feature for properties, or a way to implement it in JS?
(6 answers)
Closed 6 years ago.
I'm looking for a way to handle calls to undefined methods and properties in JavaScript.
These would be similar to the PHP magic methods __call, __callStatic, __get.
An example of the code using this might be:
var myObject = {};
myObject.__call = function (called, args) {
alert(called);
alert(args);
return(true);
}
myObject.meow("kitty", "miau");
This would result in the first alert dialog displaying "meow" and the second to display "kitty, miau".
Proxy can do it! Proxy can do EVERYTHING! An answer is given here: Is there a javascript equivalent of python's __getattr__ method? . To rephrase in my own words:
var myObject = new Proxy({},{get(target,name) {
return function() {
alert(name)
console.log(arguments) // alerts are bleh
return true
}
}})
myObject.meow("kitty", "miau") // alerts "meow", logs ["kitty","miau"] to the console, and returns true
Check out the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
Works in chrome, firefox, and node.js. Downsides: doesn't work in IE - freakin IE. Soon.
If you just want something like PHP's features, read the following solution I came up with. I'm assuming that you'll be putting this functionality on your own objects. Well, as long as they're not functions, you can have the following convention for convenience, and it should work on all browsers:
instead of myobj.foo or myobj['foo'], just use myobj('foo'), and make your object callable when you define it. But you'll have to avoid the use of "new" because "new" can never return a function in Javascript.
var NewFlexible = function() {
var custom = {};
return function(prop) {
if (!(prop in custom)) custom.prop = null;
return custom.prop;
};
};
And then you can create objects like so:
myObj = NewFlexible();
Using something similar to the Douglas Crockford pattern, you could create "classes" that extend this:
var NewDerived = function(options) {
var result = {};
NewFlexible.apply(result, arguments); // parent constructor
// go on to do what you have to do
return result;
};
Or, to forget about constructors, you can just make a wrapper around objects:
var MakeFlexible = function (obj) {
return function(prop) {
if ('prop' in obj) return obj.prop;
obj.prop = null; return obj.prop;
};
}
You'll just have to publish this documentation for all users of your code. It's actually good to expose your functionality through this convention because you don't want to freak people out by using nonstandard javascript.
There is a magic function in Javascript called __noSuchMethod__. Here's an example:
var foo = { __noSuchMethod__ : function(name,params) { alert('invalid function call'); } }
foo.bar();
EDIT: As #jldupont mentioned, this is actually only in Rhino and SpiderMonkey (Mozilla's JS engine); it is not supported in the ECMAScript standard. There are some requests that it be in ECMAScript 4.
I should add for people still looking for a solution, there is this:
var myObject = {};
myObject['dynamicMethod'] = new function (parameters) {
alert(parameters);
};
The only difference here is that you may have to iterate over what you intend on adding. This is pre-generating the methods, instead of simply dynamically handling them.
If you are looking specifically for a method, you will have to wait until ES7, because it looks they arent going to include it that way in harmony, anyway, there is a currently working-standard functionality on this, trought the built-in object Proxy, that is added in ES6, i wrote an answer, in this question, that takes the problem in a wider manner.
Basically involves wrapping the object into a proxy, an loading a handler
get: function(obj, propname) {custom handling}
into the proxy trought it´s constructor, to handle, filter or implement all requests of properties into it.
And it adds even more functionality.... For the complete answer, go into the link.

Categories