Recently really is a bit of learning and work enthusiasm are not, let me once feel sick, but there is no way ah, the front end of the brick have to work hard ah, today to sum up ~
How do I implement a new
Let’s start by summarizing the use of call and apply D
call
The first argument to the call method is the value to bind to this, followed by a list of arguments. When the first parameter is null, undefined, the default point is window.
Look at an example:
Output: My name is Dot Dolby
apply
Apply takes two arguments, the first being the value to bind to this and the second being an array of arguments. When the first parameter is null, undefined, the default point is window.
The only difference is that when a function needs to pass multiple variables, Apply accepts an array as input, while call accepts a series of individual variables.
New
First understand the new keyword call function are specific process, then write out very clear
1. First create an empty object whose __proto__ attribute points to the constructor’s prototype object 2. The empty object created above is assigned to this inside the constructor, and the empty object 3 is modified using methods inside the constructor. If the constructor returns a value of a non-primitive type, that value is returned, otherwise the object created above
function _new(fn, ... arg) { var obj = Object.create(fn.prototype); const result = fn.apply(obj, ... arg); return Object.prototype.toString.call(result) == '[object Object]' ? result : obj; }Copy the code
Preliminary completion of ~ inadequate welcome guidance!
See you next time!