0

I am trying to add a function to the Object prototype. For now, I'm simply doing this:

Object.prototype.consoleThis = function () {
    console.log(this);
};

Then embedding the code into the head. Then I try to use the new function:

var basicObject = {"name": "basicObject"};
basicObject.consoleThis();

However, in the console, a paragraph element from my HTML has been logged into the console, like so:

<p id="comment" class="ng-binding">
    This is a comment
</p>

Which is followed by the expected logging of the basicObject object. Why is this? How can I stop this from happening?

Edit: Found the source

In my JavaScript, the new function is called like so, including surrounding JavaScript:

$(document).ready(function(){
    $("#codeComments").css({height: $(".codeViewPre").height()});
    var basicObject = {
        "f": "abvc"
    };
    basicObject.consoleThis();
});

Removing the $("#codeComments").css({height: $(".codeViewPre").height()}); line removes the logged paragraph from the console. Unfortunately, I don't see why this is happening.

Xanco
  • 874
  • 1
  • 10
  • 15
  • That's one of the risks of assigning to `Object.prototype`. You can impact third-party code which doesn't expect `Object.prototype` to be extended. You might solve this by using `Object.defineProperty` and make the property non-enumerable. – Felix Kling Aug 30 '14 at 18:32
  • 2
    Please check if that paragraph is logged by this function only. There is a high chance that you have logged it by some other `console.log` and missing it now. – nisargjhaveri Aug 30 '14 at 18:33
  • I am currently using the following 3rd part libraries, if anybody knows of any potential errors with extending the prototype with these libraries; Angular.js, Prisim.js and jQuery. – Xanco Aug 30 '14 at 18:34
  • Removing this function removes the logging of the paragraph. – Xanco Aug 30 '14 at 18:35
  • Is the paragraph logged if you add the method to `Object.prototype`, but do not call `basicObject.consoleThis();`? – Bergi Aug 30 '14 at 18:36
  • @Bergi Yes, the paragraph is logged regardless if the function is never actually called – Xanco Aug 30 '14 at 18:38
  • 1
    If you use [`console.trace()`](https://developer.mozilla.org/en-US/docs/Web/API/console.trace), you will know where it comes from. – Oriol Aug 30 '14 at 18:38
  • Unless a 3rd party library makes a statement that extending `Object.prototype` is safe to do with their library, I would work with the assumption that it's unsafe. It's definitely unsafe with jQuery. – cookie monster Aug 30 '14 at 18:42
  • I have found the source of the issue, My question isn't a dupe though. There is this line before it in my JavaScript: $("#codeComments").css({height: $(".codeViewPre").height()}); Removing this removes the mystery logging. – Xanco Aug 30 '14 at 18:44

0 Answers0