Last active
February 15, 2017 09:11
-
-
Save softwarespot/9643d7153e45b3f874b3a9c6e0936ed4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ArrayObject(arr) { | |
arr.forEach((value, index) => { | |
this[index] = value; | |
}); | |
this.guid = 'RANDOM_ARRAY_LIKE_GUID_' + Math.floor(Math.random() * 9999); | |
// Create an immutable length property | |
Object.defineProperty(this, 'length', { | |
value: arr.length | |
}); | |
return this; | |
} | |
function ArrayLike(arr) { | |
arr.forEach((value, index) => { | |
this[index] = value; | |
}); | |
this.guid = 'RANDOM_ARRAY_LIKE_GUID_' + Math.floor(Math.random() * 9999); | |
// Create an immutable length property | |
Object.defineProperty(this, 'length', { | |
value: arr.length | |
}); | |
return this; | |
} | |
// This is the "magical" part, of making the ArrayLike object appear to be an array | |
ArrayLike.prototype.splice = Array.prototype.splice; | |
var obj = new ArrayObject([1, 2, 3, 4]); | |
console.log(obj); | |
var arr = new ArrayLike([1, 2, 3, 4]); | |
console.log(arr); | |
console.log(arr.guid); | |
// A micro task | |
var _guid = 0; | |
function setTimeoutMicro(fn) { | |
var node = document.createTextNode(''); | |
var observer = new MutationObserver(function () { | |
observer.disconnect(); | |
fn(); | |
}); | |
observer.observe(node, { | |
characterData: true | |
}); | |
node.data = String(++_guid); | |
} | |
setTimeout(function () { | |
console.log('A'); | |
}); | |
setTimeout(function () { | |
console.log('B'); | |
}); | |
// This is called before setTimeout | |
setTimeoutMicro(function () { | |
console.log('C'); | |
}); | |
var id = 0; | |
for (var i = 0; i < 3; i++) { | |
setTimeoutMicro(function() { | |
setTimeout(function() { | |
console.log(Date.now(), ++id); | |
}, 500); | |
}); | |
} | |
var _bindId = 0; | |
function Class(config) { | |
// Here we extend the current instance with the config object, and since the second config | |
// contains a method property already, it will override our this.method with the one that is bound to the | |
// previous context | |
Object.assign(this, config); | |
this.method = bind(this.method); | |
} | |
Class.prototype.method = function () { | |
console.log(this.id); | |
}; | |
// Basic Function.prototype.bind | |
function bind(fn) { | |
return function () { | |
console.log('Global Bind Id::', _bindId++); | |
return fn(); | |
} | |
} | |
// Demo | |
var pos1 = new Class({ | |
id: 123 | |
}); | |
var pos2 = new Class(pos1); | |
// You would expect this to print Global Bind Id 0 & 1, but it will also print 2 | |
pos1.method(); | |
pos2.method(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment