JavaScript Object Properties
Description
To think like a JavaScript hacker, we need to practice making unusual objects. Engine developers have historically made mistakes when it comes to the intricacies of object interactions.
Exercise
Using what we have learned about objects and properties, construct an object which will cause the quiz
function to call the win
function.
JavaScriptfunction quiz(obj) {
for (let name of Object.keys(obj)) {
delete obj[name];
}
if (obj.win) {
win('You win!');
} else {
console.log('You lose...');
}
}
quiz(... your object here ...)
Reveal Answer
There are several ways to do this:
JavaScriptlet obj = {};
Object.defineProperty(obj, 'win', {value:true, configurable:false})
quiz(obj); // You win!
JavaScriptlet obj = {};
obj.__proto__ = {win:1};
quiz(obj); // You win!
JavaScriptlet obj = {win: 1};
let objp = new Proxy(obj, {
deleteProperty: function(obj, prop) {
return false;
}
});
quiz(objp);
Can you find any others?