This is the first day of my participation in Gwen Challenge
new
In JS we always get the instance by new a constructor. This instance can then invoke methods on the prototype chain. The implementation of new is actually very simple. In a nutshell, it does four things
- Create a new object
- Points the __proto__ of the new object to the constructor’s prototype chain
- Call the constructor and point this to the current new object.
- Determine the return value of the constructor and decide what to return.
Look directly at the following code.
function myNew(ctor,... args) { if(typeof ctor ! == 'function') { throw new Error('type error') } let obj = new Object(); // Obj. __proto__ = object.create (ctor. Prototype); let res = ctor.aply(obj,args); Const isObject = typeof res == "object" && typeof res! == "null"; const isFunction = type of res === 'function'; return isObject || isFunction ? res : obj }Copy the code
bind
Bind returns a new function that specifies this.
The main difficulty with bind is that when the function that bind returns is used as a constructor, the value of this specified in bind is invalid, but the arguments passed in are still valid.
If you understand how new works, you’ll need to understand how bind works. That’s what happens after I bind this once, if I use the function that bind returns as a constructor to go to new. Since new also changes this, we make a this judgment to ensure that the instance’s attributes are not manually affected.
Conclusion:
In the book JavaScript Patterns, the process of new is fairly straightforward. When we create a new constructor, there are three main steps:
• Create an empty object and assign its reference to this, inheriting the prototype of the function. • Add properties and methods to this object via this • Finally return the new object to which this points, i.e. the instance (if no other object is returned manually)
I have seen a description that accords with my mind and principle in winter’s relearning front column:
• Create a new object based on the constructor’s Prototype property;
• Pass this(the new object in the previous sentence) and call parameters to the constructor, execute;
• If the constructor does not manually return an object, the new object created in the first step is returned; if it does, the new object created in the first step is discarded and the manually returned object is returned.
Bind looks like this:
- Bind the this pointer in the function that calls bind() to an object, the second and subsequent arguments to bind as arguments to the initial function, and bind() returns a new function.
- If the new function is called with the new character, the previous this reference bound to an object will be invalid, and the this reference in the original function will be bound to the function instance of the new call. A function instance can also call a method on the prototype of the original function
Welcome to Star on My Handwriting Polyfily on Github.