This is the 17th day of my participation in the August Challenge.
Deconstruction assignment
// Examine the JS object destruct assignment
// What is the result of executing the following code
var { ...obj } = Object.create({ a: 1 });
console.log(obj.a);
Copy the code
Answer: undefined
instructions
Let’s start with object.create:
The object.create () method creates a new Object, using an existing Object to provide the __proto__ of the newly created Object. From (MDN)
That is, object.create ({a: 1}) returns a new Object with the specified prototype Object and attributes {a: 1}. So the output object.create ({a: 1}) is an empty Object with a property on its prototype chain
Deconstruction assignment does not deconstruct properties on the prototype chain
So obj is {}, and its prototype chain does not have the property A.
Stack and task execution
// Look at the stack execution of JS
// Stack overflow occurs when the following code is executed: Or do you do it all the time?
function func() {
console.log(Date.now())
setTimeout(func, 0);
}
func();
Copy the code
Answer: Always
instructions
- When you call a func function, you put it on the “call stack”
- When dealing with the call stack, execute the setTimeout method and the call stack clears
- SetTimeout is 0, func will be put into the “task queue”
- Since the “call stack” is empty, the event loop puts the func from the “task queue” into the “call stack” for execution
- Repeating setTimeout again does not cause a stack overflow
One more example of overflow
function runStack (n) {
if (n === 0) return 100;
return runStack( n- 2);
}
runStack(50000)
Copy the code
Answer: Stack overflow
instructions
This is an example of a call stack that cannot be emptied, causing it to overflow
Reflect.ownKeys
Object.prototype.a = '111';
var obj = {
[Symbol('a')]: '222'
};
Object.defineProperty(obj, 'b', {
value: '333'
});
const keys = Reflect.ownKeys(obj);
console.log(keys.length)
Copy the code
Answer: 2
instructions
Reflect.ownkeys () yields all of the object’s own properties, including non-enumerable and Symbol properties, but does not retrieve the properties on the prototype. There are several points to master on this exam
- Object.defineProperty
- Reflect.ownKeys
Let’s start with Object.defineProperty
The object.defineProperty () method directly defines a new property on an Object, or modifies an existing property of an Object, and returns the Object.
The static method reflect.ownkeys ()** returns an array of the target object’s own property keys.