Using Proxy with wrapper objects around primitives [duplicate] - javascript

This question already has answers here:
How to determine that a JavaScript function is native (without testing '[native code]')
(2 answers)
Closed 4 years ago.
I want to use javascript's Proxy objects to augment a data structure with a bit of additional logging. While doing so, I noticed a problem:
simpleProxy = new Proxy(new Number(4), {})
simpleProxy.valueOf(); // TypeError: valueOf method called on incompatible Proxy
The error makes sense to me. valueOf is invoked with the this object set to the Proxy instead of the Number object thus leading to a type error.
The problem to me now is that in user code it is actually useful to propagate the Proxy as the this value into function calls so that access to properties is done through the proxy. Only when calling "low-level" routines like the above do I get in trouble. The question: How can I reliably detect that I'd be calling such a Proxy incompatible function, possibly assuming for a moment that user defined functions are safe to call?
This is not asking if the called function is a native function. Only certain native functions can not handle Proxy values. Besides, the detection in the linked question is rather unsound and would require different special cases here. Consider a function linked from a native interface. It may very well be able to operate on a proxy value, thus detecting it as a native function would be a false positive.
Currently, I believe the best approach is to find out if the target in get is primitive by calling target.valueOf() first instead of infering anything from whether the function is native or not. As such, this is not a duplicate.

First we check if the Property is from the prototype or from the target itself, if not and the key is that of a method, we return an anonymous function that passes its arguments into the method with the appropriate this when called.
Note: I'm not entirely sure if this is foolproof.
let a = new Proxy(new Number(3), {
get(target, key) {
if (!target.hasOwnProperty(key) && typeof target[key] === "function") {
return function(...args) {
return target[key].call(target, args);
}
}
return target[key];
}
});
console.log( a.valueOf() );

Related

V8: ES6 proxies don't support iteration protocol when targeting custom objects?

I'm using the V8 API to create JavaScript objects. Some of these objects support iteration by setting up a native (intercepted) function at the Symbol.iterator property.
Iterating such an object via for...of works perfectly. However, if I wrap it in a null proxy (e.g., let x = new Proxy(obj, {});), the resulting object is not iterable and throws a TypeError with the message "Illegal invocation" if an attempt is made to iterate over it.
Wrapping a standard array doesn't exhibit this issue. Is this a V8 bug?
Wrapping a standard array doesn't exhibit this issue.
Yes, that's how array iterators work. They don't care about the kind of the object they are iterating - they simply access its .length and indexed properties (which are routed normally through the proxy).
However, other standard exotic objects don't behave that nice either. If you try to invoke [Symbol​.iterator]() on a typed array, map or set that is wrapped in a proxy, they'll bitch about being invoked on the wrong object.
Is this a V8 bug?
No, it's a bug in the application. You've got three choices:
Create an iterator that does not depend on the internal slots of your custom objects, but rather uses their public (proxy-interceptable) property interface. Make sure your [Symbol.iterator] method does not typecheck its receiver.
Check the type of the receiver in your iterator method, and if it is a proxy (i.e. has a [[ProxyTarget]] internal slot) then use that value. I would strongly advise against this, as it does not match the standard behaviour and breaches the proxy when bypassing the handler.
Don't use a null proxy:
let x = new Proxy(obj, {
get(target, key, receiver) {
if (key === Symbol.iterator)
return target[Symbol.iterator].bind(target);
else
return Reflect.get(target, key, receiver);
}
});

Is there a way to check if a native Javascript function was monkey patched?

For example I loaded a script on some website, and I would like to know if JSON.parse/stringify wasn't monkey patched.
I noticed that if I use toString on the function in Chrome/FF, JSON.stringify.toString, then I get back:
function stringify() {
[native code]
}
My question is do you think this is a good way to verify if a function was monkey patched? Also would love to hear of any other approaches to this problem.
One could easily fake JSON.stringify.toString
JSON.stringify = function() {}
JSON.stringify.toString = function() {return 'ha-ha'}
console.log(JSON.stringify); //ha-ha
A little more robust way would be to use Function.prototype.toString
Function.prototype.toString.call(JSON.stringify)
But really bad monkeypatcher could patch Function.prototype.toString as well :)
Yes, this is the only practical way to check whether or not a native function had been overridden or not.
const isNative = fn => !!fn.toString().match(/\[native code\]/)
console.log(isNative(JSON.stringify));
A more robust solution could use Function.prototype.toString() instead of direct call of fn.toString(), but both are monkeypatchable as well. The joys of JavaScript :)
The spec ( http://www.ecma-international.org/ecma-262/7.0/index.html#sec-function.prototype.tostring ) does not specify the exact string returned for a builtin function :
19.2.3.5 Function.prototype.toString
When the toString method is called on an object func, the following
steps are taken:
If func is a Bound Function exotic object, then Return an
implementation-dependent String source code representation of func.
The representation must conform to the rules below. It is
implementation dependent whether the representation includes bound
function information or information about the target function. If
Type(func) is Object and is either a built-in function object or has
an [[ECMAScriptCode]] internal slot, then Return an
implementation-dependent String source code representation of func.
The representation must conform to the rules below. Throw a TypeError
exception. toString Representation Requirements:
The string representation must have the syntax of a
FunctionDeclaration, FunctionExpression, GeneratorDeclaration,
GeneratorExpression, ClassDeclaration, ClassExpression, ArrowFunction,
MethodDefinition, or GeneratorMethod depending upon the actual
characteristics of the object. The use and placement of white space,
line terminators, and semicolons within the representation String is
implementation-dependent. If the object was defined using ECMAScript
code and the returned string representation is not in the form of a
MethodDefinition or GeneratorMethod then the representation must be
such that if the string is evaluated, using eval in a lexical context
that is equivalent to the lexical context used to create the original
object, it will result in a new functionally equivalent object. In
that case the returned source code must not mention freely any
variables that were not mentioned freely by the original function's
source code, even if these “extra” names were originally in scope. If
the implementation cannot produce a source code string that meets
these criteria then it must return a string for which eval will throw
a SyntaxError exception.
So checking for [Native Code] may or may not work depending on the interpreter. Furthermore, an implementation could well implement builtin functions as normal javascript code.
So in answer to your question, you cannot determine, is a Javascript specified way whether a builtin function has been monkey-patched.
That said it appears that Chrome and Firefox both return the [Native Code] string subject to verification on other implementations that may be a pragmatic solution.
I just wanted to add that, after ES6, all solutions that involve checking "[native code]" are even less reliable because of ES6 proxy traps.
// Example monkey-patching the Fetch API using an ES6 proxy trap
window.fetch = new Proxy(window.fetch, {
apply(fetch, that, args) {
const result = fetch.apply(that, args);
result.then((response) => {
console.log("Intercepted!", args, response);
});
return result;
}
});
// True
console.log(window.fetch.toString().includes("[native code]"));
// True
console.log(Function.prototype.toString.call(window.fetch).includes("[native code]"));
For more info, check this answer.
I tried to develop some of the ideas from other replies into a working script - here it is:
https://gist.github.com/mindplay-dk/767a5313b0052d6daf2b135fdecd775f
Paste it into the Chrome (or Edge) console and press ENTER - it'll print out a list of any constructors and class-methods not matching their native counterparts. (It does this by comparing against the native APIs in an iframe - which it creates via document.createElement, so, technically, it's possible to fool it by overriding that method, if you were intending to do so deliberately; this isn't a security tool.)
Note that this currently gives false positives for window.location, window.fetch and window.length - this appears to be because these properties aren't correctly reflected by their native browser implementations? If you know how to fix it, please post a comment.
Here is example output from a site that was incorrectly loading some IE11 polyfills into Chrome:

Does Chrome retain each object's constructor?

In Chrome's JavaScript console:
> function create(proto) {
function Created() {}
Created.prototype = proto
return new Created
}
undefined
> cc = create()
Created {}
> cc
Created {}
Created is a function private to the create function; after create completes, there are no (known to me) references to Created. Yet Chrome can show the function's name at any time, starting from the object created by it.
Chrome didn't achieve this by following the "naïve" approach:
> cc.constructor
function Object() { [native code] }
> cc.toString()
"object [Object]"
and anyway, I didn't set constructor on the proto argument passed to create:
> cc.__proto__.hasOwnProperty("constructor")
false
One guess I had is that the JavaScript VM holds on to Created for the sake of the instanceof mechanism. It is said that instanceof
tests whether an object has in its prototype chain the prototype property of a constructor.
But in the above code I typed create(), effectively passing undefined as prototype; consequently Created doesn't even have its prototype set to the actual cc.__proto__. We can verify this if we hack create to expose the Created function:
function create(proto) {
function Created() {}
Created.prototype = proto
GlobalCreated = Created
return new Created
}
now let's type
> cc = create()
Created {}
> GlobalCreated
function Created() {}
> GlobalCreated.prototype
undefined
> cc instanceof GlobalCreated
TypeError: Function has non-object prototype 'undefined' in instanceof check
My questions (all closely related):
What exactly does Chrome's JavaScript engine retain to make that object presentation in the console work? Is it the constructor function, or just the function name?
Is that retention needed for anything more substantial than console printout?
What is the effect of such retention on memory consumption? What if, for example, the constructor function (or even its name) is abnormally huge?
Is it just Chrome? I've retested with Firebug and Safari, their consoles don't present the object that way. But do they still retain the same data, for other possible purposes (e.g. due to a genuine concern inherent to a JavaScript VM)?
Late edit:
I recently revisited this question/answer, and I think I've figured out why chrome seems to "hang on" to the Created name. It's not really something that is exclusive to V8, but I think it's the result of how V8 works behind the scenes (the hidden objects I explained in my initial answer), and what V8 is required to do (to conform to the ECMAScript standard).
Any function, constructor functions or otherwise, share the same constructor and prototype-chain by default:
function Created(){};
console.log(Created.constructor);//function Function() { [native code] }
console.log(Object.getPrototypeOf(Created));//function Empty() {}
console.log(Created.__proto__);//same as above
console.log(Created.prototype);//Created {}
This tells us a few things: All functions share the native Function constructor, and inherit from a specific function instance (function Empty(){}) that is used as their prototype. However, a function's prototype property is required to be an object, that the function would return if it were called as a constructor (see ECMAScript standard).
The value of the prototype property is used to initialise the [[Prototype]] internal property of a newly created object before the Function object is invoked as a constructor for that newly created object. This property has the attribute { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }.
We can verify this easily by looking at the Created.prototype.constructor:
console.log(Created.prototype.constructor);//function Created() {}
Now let's, for a moment, list the hidden classes V8 needs to, and probably will, create in order for it to comply to the standard:
function Created(){}
Hidden classes:
Object, of course: the mother of all objects, of which Function is a specific child
Function: This native object is, as we've demonstrated, the constructor
function Empty: The prototype, from which our function will inherit
Created our empty function that will inherit from all of the above
At this stage, nothing unusual has happened, and it's self-evident that, when we return an instance of this Created constructor, the Created function will get exposed because of its prototype.
Now, because we're reassigning the prototype property you could argue that this instance will be discarded, and is lost, but from what I understand, that's not how V8 will handle this situation. Instead, it'll create an additional hidden class, that simply overrides the prototype property of its parent after this statement is encountered:
Created.prototype = proto;
Its internal structure will end up looking something like this (numbered this time, because I'll refer back to certain stages within this inheritance chain further down):
Object, of course: the mother of all objects, of which Function is a specific child
Function: This native object is, as we've demonstrated, the constructor
function Empty: The prototype, from which our function will inherit
Created our empty function that will inherit from all of the above
Created2: extends the previous class (Created), and overrides prototype
So why is Created still visible?
That's the million dollar question, to which I think I have the answer now: Optimization
V8 simply can't, nor should it be allowed to, optimize out the Created hidden class (stage 4). Why? Because what will override prototype is an argument. It's something that can't be predicted. What V8 will probably do to optimize the code is to store a hidden object 4, and whenever the create function is called, it'll create a new hidden class that extends stage 4, overriding the prototype property with whatever value is passed to the function.
Because of this, Created.prototype will always exist somewhere inside each instance's internal representation. It's also important to note you could replace the prototype property with one that actually referenced an instance of Created (with a mucked-up prototype chain, but still):
cc = create();
console.log(Object.getPrototypeOf(cc))//Object {}
cc = create(new GlobalCreated);
console.log(Object.getPrototypeOf(cc));//Created {}
How's that for a mind-bender? Inception script-writers, eat your hearts out...
Anyway, I hope all of this dribble made some sense to someone out here, if not, I do respond to comments, so corrections to mistakes I may have made, or questions regarding some part of this update that is a bit unclear are welcome...
I'll try to answer question by question, but as you say, they're all closely related, so the answers overlap up to a point.
While reading this, bare in mind that I wrote this in one go, whilst feeling a bit feverish. I am not a V8 expert, and based this on recollections of my doing some digging in the V8 internals some time ago. The link at the bottom is to the official docs, and will of course contain more accurate and up-to-date information on the subject.
What is going on
What chrome's V8 engine actually does is create a hidden class for each object, and this class is mapped to the JS representation of the object.
Or as the people at google say so themselves:
To reduce the time required to access JavaScript properties, V8 does not use dynamic lookup to access properties. Instead, V8 dynamically creates hidden classes behind the scenes.
What happens in your case, extending, creating a new constructor from a particular instance and overriding the constructor property is actually nothing more than what you can see on this graph:
Where hidden class C0 could be regarded as the standard Object class. Basically, V8 interprets your code, builds a set of C++ like classes, and creates an instance if needed. The JS objects you have are set to point to the different instances whenever you change/add a property.
In your create function, this is -very likely- what is going on:
function create(proto)
{//^ creates a new instance of the Function class -> cf 1 in list below
function Created(){};//<- new instance of Created hidden class, which extends Function cf 2
function Created.prototype = proto;//<- assigns property to Created instance
return new Created;//<- create new instance, cf 3 for details
}
Right: Function is a native construct. The way V8 works means that there is a Function class that is referenced by all functions. They reference this class indirectly, though, because each function has its own specifcs, which are specified in a derived hidden class. create, then, should be seen as a reference to create extends HiddenFunction class.
Or, if you wish, in C++ syntax: class create : public Hidden::Function{/*specifics here*/}
The Create function references a hidden function identical to create. However, after declaring it, the class receives 1 propriety property, called prototype, so another hidden class is created, specifying this property. This is the basis of your constructor. Because the function body of create, where all of this happens, this is a given, and V8 will probably be clever enough to create these classes beforehand, anyway: in C++ pseudo-code, it'll look similar to code listing 1 below.
Each function call will assign a reference to a new instance Of the hidden class described above, to the Created name, which is local to create's scope. Of course, the returned instance of create does still retain the reference to this instance, but that's how JS scopes work, and so this applies to all engines... think of closures and you'll get what I mean (I'm really struggling with this nasty fever... sorry to nag about this)
At this stage Create points to an instance of this hidden class, which extends a class that extends a class (as I tried to explain in point 2). Using the new keyword triggers behaviour defined by the Function class, of course (as it's a JS language construct). This results in a hidden class to be created which is probably the same for all instances: it extends the native object, and this has a constructor property, which references the instance of Created we've just made. The instances returned by create though are all alike. Sure their constructors may have a different prototype property, but the objects they churn out all look the same. I'm fairly confident that V8 will only create 1 hidden class for the objects create returns. I can't see why the instances should require different hidden classes: their property names & count are the same, but each instance references another instance, but that's what classes are for
Anyway: code listing for item 2, a pseudo-code representation of what Created might look like in hidden-class terms:
//What a basic Function implementation might look like
namespace Hidden
{//"native" JS types
class Function : public Object
{
//implement new keyword for constructors, differs from Object
public:
Function(...);//constructor, function body etc...
Object * operator new ( const Function &);//JS references are more like pointers
int length;//functions have a magic length property
std::string name;
}
}
namespace Script
{//here we create classes for current script
class H_create : public Hidden::Function
{};
class H_Created : public Hidden::Function
{};//just a function
class H_Created_with_prototype : public H_Created
{//after declaring/creating a Created function, we add a property
//so V8 will create a hidden class. Optimizations may result in this class
// being the only one created, leaving out the H_Created class
public:
Hidden::Object prototype;
}
class H_create_returnVal : public Hidden::Object
{
public:
//the constructor receives the instance used as constructor
//which may be different for each instance of this value
H_create_returnVal(H_Created_with_prototype &use_proto);
}
}
Ignore any (likely) syntax oddities (it's been over a year since I wrote a line of C++), and ignoring namespaces and wacky names, The listed classes are, apart from the Hidden::Function effectively all the hidden classes that will ever need to be created to run your code. All your code then does is assign references to instances of these classes. The classes themselves don't take up much space in memory. And any other engine will create just as many objects, because they, too, need to comply with the ECMAScript specs.
So I guess, looking at it like this, this sort of answers all your questions: no not all engines work like this, but this approach won't cause massive amounts of memory to be used, Yes, this does mean a lot of information/data/references to all objects is retained, but that's just an unavoidable, and in some cases happy side-effect of this approach.
Update: I did a bit more digging, and found an example of how you could add JS functions to V8 using templates, it illustrates how V8 translates JS objects/functions to C++ classes, see the example here
This is just me speculating, but I wouldn't at all be surprized to learn that the way V8 works, and this retention business is heavily used in garbage-collection and memory management in general (EG: deleting a property changing hidden classes and the like)
For example:
var foo = {};//foo points to hidden class Object instance (call id C0)
foo.bar = 123;//foo points to child of Object, which has a property bar (C1)
foo.zar = 'new';//foo points to child of C1, with property zar (C2)
delete foo.zar;//C2 level is no longer required, foo points to C1 again
That last bit is just me guessing, but it could be possible for the GC to do this.
What is this retention used for
As I said, in V8, a JS object is actually a sort-of pointer to a C++ class. Accessing properties (and this includes the magic properties of arrays, too!), is fast. Really, really fast. In theory, accessing a property is an O(1) operation.
That's why, on IE:
var i,j;
for(i=0,j=arr.length;i<j;++i) arr[i] += j;
Is faster than:
for (i=0;i<arr.length;++i) arr[i] += arr.length;
While on chrome, arr.length is faster as shown her. I also answered that question, and it, too, contains some details on V8 you may want to check. It could be that my answer there doesn't (completely) apply anymore, because browsers and their engines change fast...
What about the memory
Not a big problem. Yes, Chrome can be a bit of resource hog at times, but the JS isn't always to blame. Write clean code, and the memory footprint won't be too different on most browsers.
If you create a huge constructor, then V8 will create a larger hidden class, but if that class specifies a lot of properties already, then chances of their being a need for additional hidden classes is smaller.
And of course, each function is an instance of the Function class. This being a native (and very important) type in a functional language will most likely be a highly optimized class anyway.
Anyway: as far as memory usage is concerned: V8 does a pretty good job managing memory. Far better than IE's of old, for example. So much so that the V8 engine is used for server-side JS (as in node.js), if memory really was an issue, then you wouldn't dream of running V8 on a server that must be up and running as much as possible, now would you?
Is this just Chrome
Yes, in a way. V8 does have a special take on how it consumes and runs JS. Rather than JIT-compiling your code to bytecode and running that, it compiles the AST straight into machine code. Again, like the hidden-classes trickery, this is to increase performance.
I know I included this graph in my answer on CR, but just for completeness' sake: Here's a graph that shows the differences between chrome (bottom) and other JS engines (top)
Notice that below the bytecode instructions and the CPU, there's an (orange) interpreter layer. That's what V8 doesn't need, owing to the JS being translated into machine code directly.
The downside being that this makes certain optimizations harder to do, especially concerning the ones where DOM data and user input is being used in the code (for example: someObject[document.getElementById('inputField').value]) and that the initial processing of the code is harder on the CPU.
The upside is: once the code is compiled into machine code, it's the fastest you're going to get, and running the code is likely to cause less overhead. A bytecode interpreter is heavier on the CPU most of the time, that's why busy loops on FF and IE can cause the browser to alert the user of a "running script" asking them if they want to stop it.
more on V8 internals here
I don't know much about Chrome's internals, so this is just a guess, but it seems to me that Chrome is performing some kind of static analysis on the code which created the function, and storing that for debugging purposes.
Take a look at this example:
> function create(proto) {
object = {}
object.x = {}
x = object.x
x.func = function() {}
x.func.prototype = proto
return new object.x.func
}
undefined
> create()
x.func {}
x.func? There's no way JavaScript has any built-in way for you to access the name of the variable a function was initially assigned to. Chrome must be doing that for its own reasons.
Now look at this example:
> function newFunc() {
return function() {}
}
> function create(proto) {
object = {}
object.x = {}
x = object.x
x.func = newFunc()
x.func.prototype = proto
return new object.x.func
}
undefined
> create()
Object {}
In this example, since we created the function in a separate closure before assigning it to a variable, Chrome doesn't know the "name" of the function, so it just says "Object".
These examples lead me to guess the following answers to your questions:
What exactly does Chrome's JavaScript engine retain to make that object presentation in the console work? Is it the constructor function, or just the function name?
It performs a static analysis of the code, and stores a string containing the function's "name" somewhere.
Is that retention needed for anything more substantial than console printout?
Probably not.
What is the effect of such retention on memory consumption? What if, for example, the constructor function (or even its name) is abnormally huge?
I'm not sure, but I'm guessing it's very unlikely to be an issue. Since the name of the function is determined using static analysis, the potential size of the function name is limited by the size of variable names in the script which created it (unless perhaps you're using eval, in which case I'm not sure).
Is it just Chrome? I've retested with Firebug and Safari, their consoles don't present the object that way. But do they still retain the same data, for other possible purposes (e.g. due to a genuine concern inherent to a JavaScript VM)?
I doubt it, this seems to be something specific to Chrome used to make debugging a bit easier. As far as I can tell, there's no other reason for a feature like this to exist.
Disclaimer: I am not a Google Chrome expert, however I think that these are not browser-specific, and can be explained by basic Javascript rules.
What exactly does Chrome's JavaScript engine retain to make that
object presentation in the console work? Is it the constructor
function, or just the function name?
Each Object or Function in Javascript has its inheritance chain, going up, all the way to the basic prototype.
You can not circumvent this by setting the prototype property to undefined, although it may seem like it from the console output.
So it is the whole constructor function that is retained because of inheritance, although not available to be accessed through global scope.
Is that retention needed for anything more substantial than console
printout?
Yes, it is needed for the prototype inheritance system to work.
What is the effect of such retention on memory consumption? What if,
for example, the constructor function (or even its name) is abnormally
huge?
Yes, this can cause a memory leak if used improperly.
This is why you should always delete and clean unused variables, so these and their prototypes can get collected by the garbage collector.
Is it just Chrome? I've retested with Firebug and Safari, their
consoles don't present the object that way. But do they still retain
the same data, for other possible purposes (e.g. due to a genuine
concern inherent to a JavaScript VM)?
This should work the same way across all browsers, because prototypal inheritance works the same. I have however not specifically tested for it. Please note that the console outputs int browsers can differ, and this does not mean anything, as each browser can implement its console in its own way.
//The real method to do clone
function doClone(source, keys, values, result) {
if (source == null || typeof (source) !== "object") {
return source;
}
if (source.Clone instanceof Function) {
return source.Clone();
}
if (source instanceof Date) {
if (!(result instanceof Date)) {
result = new Date();
}
result.setTime(source.getTime());
return result;
}
else if (source instanceof Array) {
if (!(result instanceof Array)) {
result = [];
}
for (var i = 0; i < source.length; i++) {
result[i] = clone(source[i], keys, values, result[i]);
}
return result;
}
try {
if (typeof result !== "object" || result == null) {
result = new source.constructor();
} else {
result.constructor = source.constructor;
}
if (source.prototype) {
result.prototype = source.prototype;
}
if (source.__proto__) {
result.__proto__ = source.__proto__;
}
} catch (e) {
if (Object.create) {
result = Object.create(source.constructor.prototype);
} else {
result = {};
}
}
if (result != null) {
// ReSharper disable once MissingHasOwnPropertyInForeach
for (var property in source) {
if (source.hasOwnProperty(property)) {
try {
var descriptor = Object.getOwnPropertyDescriptor(source, property);
if (descriptor != null) {
if (descriptor.get || descriptor.set) {
Object.defineProperty(result, property, descriptor);
} else {
descriptor.value = clone(descriptor.value, keys, values, result[property]);
Object.defineProperty(result, property, descriptor);
}
} else {
result[property] = clone(source[property], keys, values, result[property]);
}
} catch (e) {
result[property] = clone(source[property], keys, values, result[property]);
}
}
}
}
return result;
}
//The portal of clone method
function clone(source, keys, values, result) {
var index = keys.indexOf(source);
if (index !== -1) {
return values[index];
}
result = doClone(source, keys, values, result);
index = keys.indexOf(source);
if (index !== -1) {
values[index] = result;
} else {
keys.push(source);
values.push(result);
}
return result;
}
/**
* Core functions
*/
var X = {
/**
* Clone indicated source instance
* #param {} source The source instance to be clone
* #param {} target If indicated, copy source instance to target instance.
* #returns {}
*/
Clone: function (source, target) {
return clone(source, [], [], target);
}
}
You return a new instance from create to a object called Created.
create()()
> TypeError: object is not a function
If you were to remove the 'new' keyword, then you would expose the Created function to the caller's scope.

Is it acceptable to add an attribute to a JavaScript function?

Is it acceptable to add an attribute or value to a JavaScript function?
Example:
var f = 1;
function foo (param) {
f++;
}
var fooFunc = foo;
fooFunc.dummy = f;
console.log('fooFunc: ' + fooFunc);
console.log('fooFunc.dummy: ' + fooFunc.dummy);
The above example creates a function (foo), then assigns it to a new variable (fooFunc) and then adds a dummy attribute to fooFunc.
When run, this example prints the text of the function first, and then it prints the expected value (1 in this case). When printing the function, it doesn't show any indication of the dummy value:
fooFunc: function foo(param) {
f++;
}
fooFunc.dummy: 1
JsFiddle here - open the browser's JavaScript console to see the log messages: http://jsfiddle.net/nwinkler/BwvLf/
Why does this work? And where is the dummy attribute stored, and why isn't it printed when I log the function?
Lastly, even if this works, is it a good idea (or an acceptable practice) to use this? I don't want to start an open ended discussion on this, but rather see if there's documented uses of this, or people discouraging this in JavaScript coding guidelines.
Everything except primitives ( null, undefined, number, string, boolean ) in JavaScript are objects. So functions are basically objects.
Objects in JavaScript can have properties and methods, hence functions too.
all functions inherit from Function.prototype and has certain properties ( name, length ) and methods ( .call, .apply ) coming through this chain.
It is sometimes very useful to keep properties attached to the function itself, like cache information, number of invocations etc. There is nothing wrong out in using it this way.
More details : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
Let's have a look at ECMAScript documentation (Which is the standard JavaScript is based on). Here's the 3rd. version of it:
http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf
Go to chapter 15, Native ECMAScript Objects.
15.3 > Function objects.
There's a lot of interesting information there concerning your question, but the first thing worth noticing is that function is an object.
As an object, it has attributes (predefined and that you can assign yourself).
For example, try:
console.log('fooFunc.name: ' + fooFunc.name);
It should display "foo" in your case.
Since it's documented quite well, you can use it as a standard way, though it is not so well-spread and may seem a bit unusual.
Hope this helps.
It is normal object behavior, whether "acceptable" or not.
By using the function keyword you are actually calling the native predefined Function() constructor. Like any object constructor it returns an object after building it. Like any object, the returned object can have properties, including other functions as method properties.
var adder = function(a, b){return a+b};
adder.subtracter = function(a, b){return a-b};
console.log(adder(1,2)); // 3
console.log(adder.subtracter(1,2)); // -1
TIP: if you want to see the adder object and its subtracter method, switch to DOM view from Console view after running the above code in console and then search for "adder". You'll see the object there, and then you can collapse to see what it's made from, including a subtracter object.
Of course, a function object is a special native object, which makes it possible to make calls like this: adder() and actually run some code. The fact that a function object is harder to inspect for custom attached properties, combined with its native special object treats (read built-in restrictive behavior), should give you a hint that, while it's possible, attaching custom properties is not the intended nor a good use of a function object.

JavaScript array handling - ActiveX vs. FF add-on

Question
Is there a clean and robust way to handle calls to a plugin so that the caller can always expect to have a JavaScript array returned to them, regardless of whether the plugin is a Firefox add-on or an ActiveX control? I've already got the actual plugin calls wrapped in functions, like:
function getDevice(deviceKey) {
return plugin.getDevice(deviceKey);
}
I can change it to something like:
function getDevice(deviceKey) {
return normalizeArray(plugin.getDevice(deviceKey));
}
function normalizeArray(array) {
return typeof(array) == 'unknown' ? array.toArray() : array;
}
but I still need to remember to actually call normalizeArray from the wrapper functions, and the normalize implementation seems like it could be lacking in robustness and/or making some suspect assumptions.
Is there a better way to handle this situation?
Background
I'm writing some JavaScript to interact with a plugin through JavaScript. The plugin is available as an add-on in FF and as an ActiveX in IE. There are a number of methods available in the plugin that return arrays. In FF, calling:
typeof(retVal);
on the object returns 'object'. I can do things like:
retVal.length;
retval[0];
and they work as expected. When I make those same method calls in IE, calling:
typeof(retVal);
returns 'unknown' and calls like:
retVal.length;
retval[0];
are undefined.
I've done some debugging and discovered that what the ActiveX is really returning is an array of variants. This object IS recognizable by JScript, and a JavaScript version of the array can be obtained by caling retVal.toArray().
I would make the array normalisation part of the wrapper but keep it as a separate function so:
function getDevice(deviceKey) {
return normalizeArray( plugin.getDevice(deviceKey) );
}
You're right, the normalizeArray function does seem a bit brittle. You might instead want to do an instanceof test, and even wrap it in try..catch as IE is known to do strange things when ActiveX objects are tested this way, so:
function normalizeArray(obj) {
try {
if (obj instanceof Array) {
return obj;
}
} catch(d) {}
// Convert obj to array - see if toArray property is truthy
if (obj.toArray) {
// Is this syntax correct?
// If it is, call it
return obj.toArray();
} else {
// Not Array, no toArray(), what next?
}
}
However I'm not sure if the object returned by your Firefox plugin is a javascript Array or if it's created in the same scope as the normalizeArray function (i.e. it might be created from a different Array constructor) so the instanceof test will fail even if it is an Array. An alternative test is:
Object.prototype.toString.call(obj) == '[object Array]'
which I think should definitely be wrapped in try..catch for IE if there is any chance obj is an ActiveX object.
Incidentally, typeof is an operator, there is no need to use the grouping operator ().

Categories