Adding a function to the prototype of an object causes the function to appear in all loops "for X in OBJ"

So here is an example javascript code:

Object.prototype.simpleFunction = function () { return true; } var tempObject = {}; for (var temp in tempObject) { console.log(temp); } 

Note that if you do this, you will get "simpleFunction" from the console.log commands in Google Chrome. (I am using 19.0.1084.46m.)

However, a large number of related object functions are not passed to console.log .

How do I add functions to the Object prototype if they do not appear in my ' for property in ' loops?

Change I should have mentioned that the last thing I wanted to do was throw away another if statement, since that would mean I need to add it to ALL for loops :(

+4
source share
4 answers

This is why you should always check hasOwnProperty :

 for (var temp in tempObject) { if (Object.prototype.hasOwnProperty(tempObject, temp)) { console.log(temp); } } 

Crockford supporters use Object.prototype.hasOwnProperty instead of tempObject.hasOwnProperty , just in case you override hasOwnProperty in your object.


In ES5, you can set it not as enumerable :

 Object.defineProperty(Object.prototype, 'simpleFunction', { value: function() { return true; }, enumerable: false, // this is actually the default }); 

Alternatively (in ES5) you can use Object.keys() to get only the object’s own keys:

 Object.keys(tempObject).forEach(function(key) { console.log(key); }); 
+6
source

You mean something like:

 for (var temp in tempObject) { if (tempObject.hasOwnProperty(temp )) { console.log(temp); } } 
0
source

You can skip inherited properties by following these steps:

 if (tempObject.hasOwnProperty(temp)) { // property didn't come from the prototype chain } 

On the bottom line, you cannot add functions to the prototype without repeating them with in .

You can define an external interface in which you always pass an object, for example.

 function simpleFunction(obj) { } 
0
source

This cannot be done in javascript. You need to filter the results yourself. One possible way is to define the prototype’s own properties in another object:

 var myObjectExt = { sampleFunciton: function(){} } var p; for(p in myObjectExt){ Object.prototype[p] = myObjectExt[p]; } var obj = {}; for(p in obj){ if(myObjectExt[p])continue; //do what you need } 
0
source

Source: https://habr.com/ru/post/1413653/


All Articles