Skip to content

Instantly share code, notes, and snippets.

@KSXGitHub
Last active October 2, 2016 13:47
Show Gist options
  • Save KSXGitHub/a740a7366533306ec65fb9c9ce1a81a2 to your computer and use it in GitHub Desktop.
Save KSXGitHub/a740a7366533306ec65fb9c9ce1a81a2 to your computer and use it in GitHub Desktop.
Create a property accessor for `Object.prototype.foo` and create `{foo: bar}` to see whether `foo`'s setter being called or not
// I tested this in Node.js and Chrome browser
'use strict'
// Set things up
Object.defineProperty(Object.prototype, 'foo', {
set (x) {
console.log('Setter is called: ' + x)
this._foo = x
},
get () {
console.log('Getter is called: ' + this._foo)
return this._foo
},
enumerable: false,
configurable: false
})
console.log('Own property (root): ' + Object.prototype.hasOwnProperty('foo')) // true
// Assigning property 'foo'
const obja = {}
obja.foo = 'obja' // Setter is called: obja
obja.foo // Getter is called: obja
console.log('Own property (obja): ' + obja.hasOwnProperty('foo')) // false
// Initializing property 'foo'
const objb = {foo: 'objb'} // No effect, it's not assigning, it doesn't call foo's setter
objb.foo // Still no effect
console.log('Own property (objb): ' + objb.hasOwnProperty('foo')) // true
// As you can see, 'foo' is nothing like '__proto__'.
// While initializing '__proto__' in object literal results an object with chosen proto, initializing 'foo' has no special effect
// So I think '__proto__' must be treated specially, which implies that V8 is aware of '__proto__'
// Do you think that V8 was going to call '__proto__' setter and getter to reduce its efficiency? I think not
// I think that V8 was "Object.create(__proto__)" before caring about other properties
// 'foo = {abc: 123, __proto__: bar}' is more like 'foo = object extends bar {abc: 123}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment