Câu hỏi phỏng vấn Javascript
Câu hỏi

What is the new ke...

Câu trả lời

The new keyword in JavaScript is used to create a new instance of an object that has a constructor function. When you use new with a function, several steps are taken to create a new object:

  1. A new empty object is created.
  2. The new object's internal [[Prototype]] property (often accessible as __proto__) is set to the prototype of the constructor function, establishing the prototype chain.
  3. The this variable within the constructor function is bound to the new object, allowing properties and methods to be assigned to it using this.
  4. If the constructor function does not explicitly return a non-primitive value (i.e., an object, array, etc.), the new operator will return the new object that was created. If a non-primitive value is returned by the constructor, that value will be returned instead of the new object.

Using the new keyword ensures that each instance created is unique and has its own set of properties and methods, as defined in the constructor function. It also correctly sets up the object's prototype chain, which is essential for object inheritance in JavaScript.

The new keyword also changes the behavior of the this keyword inside the constructor function. Without new, this would refer to the global object (in non-strict mode) or...

senior

senior

Gợi ý câu hỏi phỏng vấn

junior

What is a Polyfill?

middle

When should I use Arrow Functions in ES6?

middle

What advantages are using arrow functions?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào