Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does adding a property to an object literal's prototype change its "type"?
    primarykey
    data
    text
    <p>So I have a simple <code>isPlainObject</code> method that I use to test for JavaScript object literals:</p> <pre><code>var isPlainObject = function (obj) { return typeof obj === "object" &amp;&amp; {}.toString.call(obj) === "[object Object]"; }; </code></pre> <p>Now I have a plain object:</p> <pre><code>var obj = {'one': 1, 'two': 2, 'three': 3}; </code></pre> <p>When I run it through the <code>isPlainObject(obj)</code> function it works as expected and returns <code>true</code>. My question arrives from adding a property to the object's prototype:</p> <pre><code>obj.constructor.prototype.four = 4; </code></pre> <p>Now when I run <code>isPlainObject(obj)</code> on <code>obj</code> it returns <code>false</code>. <code>typeof obj</code> returns <code>object</code> in both instances. The <code>toString</code> returns <code>[object Number]</code> in the second instance after I've added a property to the prototype.</p> <p>What exactly has happened to change <code>obj</code>? What's going on?</p> <p>EDIT: This only happens when tested within the confines of a <strong>QUnit</strong> function call.</p> <pre><code>test("each", function() { _.each([1, 2, 3], function(i,v) { equal(v, i + 1, 'each iterator provided index and value from array'); }); var obj = {'one': 1, 'two': 2, 'three': 3}; console.log(_.isPlainObject(obj)); // =&gt; true obj.constructor.prototype.four = 4; console.log(_.isPlainObject(obj)); // =&gt; false }); </code></pre> <p>EDIT: This is the console.log I get when logging the <code>arguments</code> array-like object within <code>isPlainObject</code>. </p> <p><img src="https://i.stack.imgur.com/AVckV.png" alt="Logging out the &lt;code&gt;arguments&lt;/code&gt; object"></p> <p>Looking at the log would seem to indicate the array now has two arguments. But the length still reads <code>1</code>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload