const func = function() { this.name = 'mon' } let f1 = new func let f2 = Object.create(f1) let f3 = Object.create(f2) // The following comments are what the browser console logs: console.log(f1.__proto__) // {constructor: f} console.log(f2.__proto__) // func {name: "mon"} console.log(f3.__proto__) // func {} (here's where this snippet logs func {"name": "mon"})
Also, is an object's 'type' in JS determined by its 'nearest' constructor? (ie func being the type the browser logs for f1
& f2
)?
The difference is that the Stack Snippet console (whose code can be found here ) iterates over properties using for..in
. This will include enumerable properties anywhere on the prototype chain. This is (part of) how the snippet console figures out properties to log:
function n(e) {
var n = [];
for (var o in e)
n.push(o);
return n
}
For example:
const proto = { prop: 'val' }; const obj = Object.create(proto); console.log(obj); // browser console shows `Object`, but no `prop` property
In contrast, in the browser console, only properties directly on a logged object will be displayed. In order to access the internal prototype of the logged object (and see possible properties on the prototype), you'll have to click on the __proto__
property to expand it.
Because the constructor
property of a someFunction.prototype
is not enumerable, it won't be iterated over via for..in
, so it's seen in the browser console, but not in the snippet console.
const func = function() { this.name = 'mon' } console.log(func.prototype.hasOwnProperty('constructor')); for (const prop in func.prototype) { console.log(prop); // Nothing is logged }
Also, is an object's 'type' in JS determined by its 'nearest' constructor? (ie func being the type the browser logs for f1 & f2 )?
Every object has exactly one internal prototype. In your snippet, the internal prototype of f3
is f2
, the internal prototype of f2
is f1
, and the internal prototype of f1
is func.prototype
. Something in a prototype chain may also have a constructor
property ( func.prototype.constructor === func
), but the fact that such a property exists doesn't really have an effect on the internal prototype chain, it's just an convenient method to link a .prototype
object to its associated function
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.