Record some JS related content, uncomplicated technical points will be included here.
JavaScript Symbol type
Symbol is a new base type in ES6 that can itself generate a unique value. This feature can be used for:
- As a private property of the object, to avoid external calls
- Eliminate magic string
- Use as a unique variable name to avoid naming conflicts
reference
Implement the new operator?
The first thing you need to know is what new does and why you use it. A function that you don’t call with new is just a normal function.
Once you use New, everything is different. This function will be treated as a constructor, and will get an instance whether it returns or not, and when the constructor is called, this will refer to that instance.
In addition, the constructor has its prototype, and the new instance automatically inherits the prototype method.
So only need to follow the above steps to achieve, very simple:
- Create a new object instance
- Initialize the instance with the constructor
- Inherits the prototype of the constructor prototype
- Return this object instance
function myNew(constructor, data) {
let obj = {}
constructor.call(obj, data);
Object.setPrototypeOf(obj, constructor.prototype);
return obj;
}
Copy the code
Method to determine the Array type
Object.prototype.toString.call([])
Array.isArray([])
Copy the code
Call \ apply \ bind?
How it works: Using the “this always refers to the last object that called it” feature, only need to make an object method, call “need to change the method this refers to” line.
// Apply is similar to call, except that the parameters are passed differently
Function.prototype.myCall = function(context = window. args) {
context = typeof context === "object" ? context : new String(context);
context.fn = this;
letres = context.fn(... args);delete context.fn;
return res;
};
Function.prototype.myBind = function(context = window) {
context = typeof context === "object" ? context : new String(context);
context.fn = this;
let args = arguments[1];
return function() {
letres = context.fn(... args);delete context.fn;
return res;
};
};
Copy the code
Proxy versus Object.defineProperty
The advantages of Proxy
- You can listen directly on an entire object, including arrays, rather than properties.
- There are up to 13 interception methods such as
apply, ownKeys, has, deleteProperty
.
The advantage of Object. Defineproperty
- Good compatibility and support for Internet Explorer 9