I'm having to use hasOwnProperty a lot in my code and it is annoyingly long and camel-cased to type. I wanted to be able to just say myObj.has('x'), but when I tried to make an alias for hOP in the Object.prototype 'has' now gets enumerated in for..in loops. What is the best way to get what I want? I mean I could just make a global function that works like has(obj, prop) but I like the dot format better and I would like to know what tricks javascript might have up it's sleeve, so I am looking for suggestions.
Update: this seems pretty hacky but is String.prototype.in = function(obj){return obj.hasOwnProperty(this)} OK? With that I can then say if ( 'x'.in(myObj) ) {... Unfortunately it adds another layer of function call rather than just aliasing hasOwnProperty, but I like the syntax.
You can only prevent enumeration in ES5 compatible browsers, using Object.defineProperty():
Object.defineProperty(myObj, "has", { value: Object.prototype.hasOwnProperty });
defineProperty() defaults to setting non-enumerable properties. A better ES3 approach would be to just alias the function and don't stick it on Object.prototype:
var has = function (ob, prop) {
return Object.prototype.hasOwnProperty.call(ob, prop);
}
I don't see anything wrong with your own String.prototype.in approach either, except maybe potential naming collisions in the future, but that's your call. Calling it String.prototype.on would remove ambiguity with the in operator.
This should do the trick
Object.prototype.has = function(x) {
return this.hasOwnProperty(x)
}
Take care when using SomeNativeThing.prototype and use
if ((typeof Object.prototype.has) !== 'function') {
...
}
to ensure your not overriding anything
as #pomeh states, using Object.prototype.has = Object.prototype.hasOwnProperty is way better
Related
Google JavaScript Style Guide advises against extending the Array.prototype.
However, I used Array.prototype.filter = Array.prototype.filter || function(...) {...} as a way to have it (and similar methods) in browsers where they do not exist. MDN actually provides similar example.
I am aware about Object.prototype issues, but Array is not a hash table.
What issues may arise while extending Array.prototype that made Google advise against it?
Most people missed the point on this one. Polyfilling or shimming standard functionality like Array.prototype.filter so that it works in older browsers is a good idea in my opinion. Don't listen to the haters. Mozilla even shows you how to do this on the MDN. Usually the advice for not extending Array.prototype or other native prototypes might come down to one of these:
for..in might not work properly
Someone else might also want to extend Array with the same function name
It might not work properly in every browser, even with the shim.
Here are my responses:
You don't need to use for..in on Array's usually. If you do you can use hasOwnProperty to make sure it's legit.
Only extend natives when you know you're the only one doing it OR when it's standard stuff like Array.prototype.filter.
This is annoying and has bit me. Old IE sometimes has problems with adding this kind of functionality. You'll just have to see if it works in a case by case basis. For me the problem I had was adding Object.keys to IE7. It seemed to stop working under certain circumstances. Your mileage may vary.
Check out these references:
http://perfectionkills.com/extending-native-builtins/
http://blip.tv/jsconf/jsconf2011-andrew-dupont-everything-is-permitted-extending-built-ins-5211542
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
https://github.com/kriskowal/es5-shim
Good luck!
I'll give you the bullet points, with key sentences, from Nicholas Zakas' excellent article Maintainable JavaScript: Don’t modify objects you don’t own:
Dependability: "The simple explanation is that an enterprise software product needs a consistent and dependable execution environment to be maintainable."
Incompatible implementations: "Another peril of modifying objects that you don’t own is the possibility of naming collisions and incompatible implementations."
What if everyone did it?: "Simply put: if everyone on your team modified objects that they didn’t own, you’d quickly run into naming collisions, incompatible implementations, and maintenance nightmares."
Basically, don't do it. Even if your project is never going to be used by anyone else, and you're never going to import third party code, don't do it. You'll establish a horrible habit that could be hard to break when you start trying to play nice with others.
As a modern update to Jamund Ferguson's answer:
Usually the advice for not extending Array.prototype or other native prototypes might come down to one of these:
for..in might not work properly
Someone else might also want to extend Array with the same function name
It might not work properly in every browser, even with the shim.
Points 1. and 2. can now be mitigated in ES6 by using a Symbol to add your method.
It makes for a slightly more clumsy call structure, but adds a property that isn't iterated over and can't be easily duplicated.
// Any string works but a namespace may make library code easier to debug.
var myMethod = Symbol('MyNamespace::myMethod');
Array.prototype[ myMethod ] = function(){ /* ... */ };
var arr = [];
// slightly clumsier call syntax
arr[myMethod]();
// Also works for objects
Object.prototype[ myMethod ] = function(){ /* ... */ };
Pros:
For..in works as expected, symbols aren't iterated over.
No clash of method names as symbols are local to scope and take effort to retrieve.
Cons:
Only works in modern environments
Slightly clunky syntax
Extending Array.prototype in your own application code is safe (unless you use for .. in on arrays, in which case you need to pay for that and have fun refactoring them).
Extending native host objects in libraries you intend others to use is not cool. You have no right to corrupt the environment of other people in your own library.
Either do this behind an optional method like lib.extendNatives() or have [].filter as a requirement.
Extending Natives and Host Objects
Prototype does this. It's evil. The following snippet demonstrates how doing so can produce unexpected results:
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script language="javascript">
a = ["not", "only", "four", "elements"];
for (var i in a)
document.writeln(a[i]);
</script>
The result:
not only four elements function each(iterator, context) { var index = 0; . . .
and about 5000 characters more.
I want to add an additional answer that allows extending the Array prototype without breaking for .. in loops, and without requiring use of hasOwnPropery:
Don't use this bad approach which causes prototype values to appear in for .. in:
Array.prototype.foo = function() { return 'foo'; };
Array.prototype.bar = function() { return 'bar'; };
let a = [ 1, 2, 3, 4 ];
console.log(`Foo: ${a.foo()}`);
console.log(`Bar: ${a.bar()}`);
console.log('==== Enumerate: ====');
for (let v in a) console.log(v);
Instead use Object.defineProperty, with enumerable: false - it exists for pretty much exactly this reason!
Object.defineProperty(Array.prototype, 'foo', {
value: function() { return 'foo'; },
enumerable: false
});
Object.defineProperty(Array.prototype, 'bar', {
value: function() { return 'bar'; },
enumerable: false
});
let a = [ 1, 2, 3, 4 ];
console.log(`Foo: ${a.foo()}`);
console.log(`Bar: ${a.bar()}`);
console.log('==== Enumerate: ====');
for (let v in a) console.log(v);
Note: Overall, I recommend avoiding enumerating Arrays using for .. in. But this knowledge is still useful for extending prototypes of classes where enumeration is appropriate!
Some people use for ... in loops to iterate through arrays. If you add a method to the prototype, the loop will also try to iterate over that key. Of course, you shouldn't use it for this, but some people do anyway.
You can easily create somekind of sandbox with poser library.
Take a look on https://github.com/bevacqua/poser
var Array2 = require('poser').Array();
// <- Array
Array2.prototype.eat = function () {
var r = this[0];
delete this[0];
console.log('Y U NO .shift()?');
return r;
};
var a = new Array2(3, 5, 7);
console.log(Object.keys(Array2.prototype), Object.keys(Array.prototype))
I believe this question deserves an updated ES6 answer.
ES5
First of all, as many people have already stated. Extending the native prototypes to shim or polyfill new standards or fix bugs is standard practice and not harmful. For example if a browser doesn't support the .filter method if (!Array.prototype.filter) you are free to add this functionality on your own. In-fact, the language is designed to do exactly this to manage backwards compatibility.
Now, you'd be forgving for thinking that since JavaScript object use prototypal inheritance, extending a native object like Array.prototype without interfering should be easy, but up until ES6 it's not been feasible.
Unlike objects for example, you had to rely and modifying the Array.prototype to add your own custom methods. As others have pointed out, this is bad because it pollutes the Global namespace, can interfere with other code in an unexpected way, has potential security issues, is a cardinal sin etc.
In ES5 you can try hacking this but the implementations aren't really practically useful. For more in depth information, I recommend you check out this very informative post: http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/
You can add a method to an array, or even an array constructor but you run into issues trying to work with the native array methods that rely on the length property. Worst of all, these methods are going to return a native Array.prototype and not your shiny new sub-class array, ie: subClassArray.slice(0) instanceof subClassArray === false.
ES6
However, now with ES6 you can subclass builtins using class combined with extends Array that overcomes all these issues. It leaves the Array.prototype intact, creates a new sub-class and the array methods it inherits will be of the same sub-class! https://hacks.mozilla.org/2015/08/es6-in-depth-subclassing/
See the fiddle below for a demonstration:
https://jsfiddle.net/dmq8o0q4/1/
Extending the prototype is a trick that only works once. You do and you use a library that also does it (in an incompatible way) and boom!
The function you are overriding could be used by the internal javascript calls and that could lead to unexpected results. Thats one of the reasons for the guideline
For example I overrode indexOf function of array and it messed up accessing array using [].
I was working on an AJAX-enabled asp.net application.
I've just added some methods to Array.prototype like
Array.prototype.doSomething = function(){
...
}
This solution worked for me, being possible reuse code in a 'pretty' way.
But when I've tested it working with the entire page, I had problems..
We had some custom ajax extenders, and they started to behave as the unexpected: some controls displayed 'undefined' around its content or value.
What could be the cause for that? Am I missing something about modifing the prototype of standart objects?
Note: I'm pretty sure that the error begins when I modify the prototype for Array. It should be only compatible with IE.
While the potential for clashing with other bits o' code the override a function on a prototype is still a risk, if you want to do this with modern versions of JavaScript, you can use the Object.defineProperty method, e.g.
// functional sort
Object.defineProperty(Array.prototype, 'sortf', {
value: function(compare) { return [].concat(this).sort(compare); }
});
Modifying the built-in object prototypes is a bad idea in general, because it always has the potential to clash with code from other vendors or libraries that loads on the same page.
In the case of the Array object prototype, it is an especially bad idea, because it has the potential to interfere with any piece of code that iterates over the members of any array, for instance with for .. in.
To illustrate using an example (borrowed from here):
Array.prototype.foo = 1;
// somewhere deep in other javascript code...
var a = [1,2,3,4,5];
for (x in a){
// Now foo is a part of EVERY array and
// will show up here as a value of 'x'
}
Unfortunately, the existence of questionable code that does this has made it necessary to also avoid using plain for..in for array iteration, at least if you want maximum portability, just to guard against cases where some other nuisance code has modified the Array prototype. So you really need to do both: you should avoid plain for..in in case some n00b has modified the Array prototype, and you should avoid modifying the Array prototype so you don't mess up any code that uses plain for..in to iterate over arrays.
It would be better for you to create your own type of object constructor complete with doSomething function, rather than extending the built-in Array.
What about Object.defineProperty?
There now exists Object.defineProperty as a general way of extending object prototypes without the new properties being enumerable, though this still doesn't justify extending the built-in types, because even besides for..in there is still the potential for conflicts with other scripts. Consider someone using two Javascript frameworks that both try to extend the Array in a similar way and pick the same method name. Or, consider someone forking your code and then putting both the original and forked versions on the same page. Will the custom enhancements to the Array object still work?
This is the reality with Javascript, and why you should avoid modifying the prototypes of built-in types, even with Object.defineProperty. Define your own types with your own constructors.
There is a caution! Maybe you did that: fiddle demo
Let us say an array and a method foo which return first element:
var myArray = ["apple","ball","cat"];
foo(myArray) // <- 'apple'
function foo(array){
return array[0]
}
The above is okay because the functions are uplifted to the top during interpretation time.
But, this DOES NOT work: (Because the prototype is not defined)
myArray.foo() // <- 'undefined function foo'
Array.prototype.foo = function(){
return this[0]
}
For this to work, simply define prototypes at the top:
Array.prototype.foo = function(){
return this[0]
}
myArray.foo() // <- 'apple'
And YES! You can override prototypes!!! It is ALLOWED. You can even define your own own add method for Arrays.
You augmented generic types so to speak. You've probably overwritten some other lib's functionality and that's why it stopped working.
Suppose that some lib you're using extends Array with function Array.remove(). After the lib has loaded, you also add remove() to Array's prototype but with your own functionality. When lib will call your function it will probably work in a different way as expected and break it's execution... That's what's happening here.
Using Recursion
function forEachWithBreak(someArray, fn){
let breakFlag = false
function breakFn(){
breakFlag = true
}
function loop(indexIntoSomeArray){
if(!breakFlag && indexIntoSomeArray<someArray.length){
fn(someArray[indexIntoSomeArray],breakFn)
loop(indexIntoSomeArray+1)
}
}
loop(0)
}
Test 1 ... break is not called
forEachWithBreak(["a","b","c","d","e","f","g"], function(element, breakFn){
console.log(element)
})
Produces
a
b
c
d
e
f
g
Test 2 ... break is called after element c
forEachWithBreak(["a","b","c","d","e","f","g"], function(element, breakFn){
console.log(element)
if(element =="c"){breakFn()}
})
Produces
a
b
c
There are 2 problems (as mentioned above)
It's enumerable (i.e. will be seen in for .. in)
Potential clashes (js, yourself, third party, etc.)
To solve these 2 problems we will:
Use Object.defineProperty
Give a unique id for our methods
const arrayMethods = {
doSomething: "uuid() - a real function"
}
Object.defineProperty(Array.prototype, arrayMethods.doSomething, {
value() {
// Your code, log as an example
this.forEach(v => console.log(v))
}
})
const arr = [1, 2, 3]
arr[arrayMethods.doSomething]() // 1, 2, 3
The syntax is a bit weird but it's nice if you want to chain methods (just don't forget to return this):
arr
.map(x=>x+1)
[arrayMethods.log]()
.map(x=>x+1)
[arrayMethods.log]()
In general messing with the core javascript objects is a bad idea. You never know what any third party libraries might be expecting and changing the core objects in javascript changes them for everything.
If you use Prototype it's especially bad because prototype messes with the global scope as well and it's hard to tell if you are going to collide or not. Actually modifying core parts of any language is usually a bad idea even in javascript.
(lisp might be the small exception there)
I've written a js lib that needs to work in ie8 and I've been asked not to use jQuery as part of the implementation. Part of the js lib requires searching an array for a matching value. Modern browsers support the array indexOf() function which will accomplish this. However, since my js lib needs to support ie8 I won't be able to use this function. Initially I wrote the following custom function:
function inArray(anArray, aValue)
{
for (var i = 0; i < anArray.length; i++)
if (anArray[i] === aValue) return true;
//value was not in array
return false;
}
However, this morning it occured to me that it would be better to write this using prototypal inheritance. What would be a good way to rewrite this using prototypal inheritance? Also, is there a way I can go into the direct source code used for the ES standard, copy the indexOf() function and paste it into my custom js lib? Not sure if this is possible or not but it seems like a good way to port snippets without reinventing the wheel.
You're probably best off with a utility function you pass the array into, such as the inArray in your question.
You could add a shim for Array#indexOf or includes or similar to Array.prototype, but if you did, it would become enumerable and show up in for-in loops. People shouldn't use for-in to loop through arrays, but sadly, they sometimes do. If they do in your codebase or any library your codebase includes, that will be a problem.
Unfortunately, you can't make it non-enumerable because IE8 doesn't support Object.defineProperty (except on HTML elements, oddly).
As a general rule, having your own namespace and using a function like you've described is probably better for a library, something like this:
MyLib.inArray = function(array, value) {
// implementation here
};
You could modify the prototype of Array with the ES6 function .includes() like so:
Array.prototype.includes = Array.prototype.includes || function(needle) {
// implementation here
};
and then you can use it like so:
[1, 2, 3].includes(3); // true
(Note that if it already exists, we don't override it)
However, this is generally bad practice to do in a library, because you're modifying a reference to a build-in function that other scripts on the page may rely on! Additionally, properties added this way will show up when iterating the array with for..in, which is extremely undesirable.
Now that I'm programming in javascript more and more often, there's a task I'm coming across quite often that I wonder could be dealt with more elegantly.
It's about checking whether a variable, values say, is an array of Xs, or rather just an X, immediatly followed by an iteration over it or its elements.
(X being object, string, number, ... anything really -- except array).
Especially when dealing with xml or json files, a single X is not wrapped in [ ] to make it a 1-element array, and my code breaks if I don't watch out.
I deal with this now in the following way:
if (!(values instanceof Array)) values = [values]
values.forEach(function(value){/*do stuff with value*/});
For now, I've written a function to take care of this,
function arrayIfNot(arr) {return (arr instanceof Array) ? arr : [arr];}
Which I can use as
arrayIfNot(values).forEach(function(value){/*do stuff with value*/});
but as it is such a common task, I'd be surprised if there isn't a common shortcut or library function (jQuery?) to do this.
Thanks!
EDIT:
I suppose I could extend the prototypes like so (haven't tried):
Array.prototype.toArray = function () {return this;};
String.prototype.toArray = function () {return [this];};
...
so that I could do
values.toArray().forEach(function(value){/*do stuff with value*/});
but I'm always warned against extending the prototype. What do you think?
Thanks again!
Personally, I've adopted this idiom:
[].concat(a)
This takes advantage of the behavior of concat, which is that if its argument is a scalar, it just adds it to the array; if it is an array, it adds each of its elements.
There is a common way to do this in modern browsers, it's Array.isArray, and it's supported from IE9 and up.
MDN has a polyfill for non-supporting browsers.
jQuery has it's own version, jQuery.isArray
For your specific example, a common way to do it is
values = Array.isArray(values) ? values : [values];
If you're willing to use a library, Underscore.js has a lot of fantastic additions to basic JavaScript. Using Underscore, I commonly do something like this:
function myFunction(arg) {
arrayArg = _.flatten([arg])
}
If your arg might itself contain arrays which you need to preserve, just add true as a second argument to flatten.
For example; the function alert or writeln; how could I find which interface these functions come from programmatically within JavaScript?
Yes, like this:
if (typeof(yourFunction) !== "undefined") {
// do something, like call the function
}
You can easily check to see that a function is defined with typeof:
if (typeof(maybeFunction) === "function") {
// do something
}
On the other hand, it is not easy in general to know where a function is defined. Different browsers host their core functional implementations in different places, and furthermore it is incredibly easy to copy references to functions:
var myAlert = alert; // Now myAlert is a function,
// but where will you find a function myAlert() declaration? Nowhere...
So I think the proper answer to your question is, it's not possible (in general). You can use a debugger to find it on the fly, or a good text editor or grep tool to find it offline, but you won't be able to find it programatically.
If you want to "list an objects functions", you can do:
function listOwnMethods(obj) {
var ownMethods = [];
for (var p in obj) {
if (obj.hasOwnProperty(p) && typeof obj[p] == 'function') {
ownMethods.push(p);
}
}
return ownMethods;
}
However, this will not list the non–enumerable properties. If you want to also get enumerable inherited methods, remove the hasOwnProperty test.
Some versions of JavaScript also have getters and setters, so properties may behave like functions even though their Type is not "function". Finally, host objects can return anything they like when tested with typeof, so you may not be able to determine all (or even any) of a host object's methods that way.