1. Extend methods on the original prototype of the built-in class
(1) It is convenient to call the method directly based on the instance. In the method, this is the instance “which is the value we want to operate”.
(2) Can realize the chain call
(3) It is better to set the prefix “myXxx” to prevent the extension method from overwriting the original built-in method
let arr = [10, 20];
console.log(arr.slice(1).map(item => item * 10).push('X').toFixed(2).split('.'));
Copy the code
2. In strict mode, this is the corresponding object type; in non-strict mode, this is the basic type
Number.prototype.plus = function plus(val) {
val = checkVal(val);
return this + val;
};
Copy the code
3. Implement the following
let n = 10; let m = n.plus(10).minus(5); console.log(m); //=>15 (10+10-5) encapsulate: const checkVal = val => {val = +val; return isNaN(val) ? 0 : val; }; Number.prototype.plus = function plus(val) { val = checkVal(val); return this + val; }; Number.prototype.minus = function minus(val) { val = checkVal(val); return this - val; };Copy the code
4. Multiple roles of functions
/* * Function's various roles * + function * + common function "closure scope" * + constructor "class, instance" * + generator function * + object */Copy the code
(1) Array
-
Array is both a function and an object; Is a constructor that is also an instance of Function
-
Array.from converts a class Array to an Array
- The array. length property represents the number of arguments I need to pass in when I use the constructor
- Array.name: is the name of the constructor
- Array as a whole:
(2) the Object
- As a distinction between object and function j
(3) Function
- Function. Prototype is an anonymous empty Function; But even though it is a function, it has no prototype property
It’s the same prototype as the other constructors
- The Function diagram
- The little knowledge
No prototype function (cannot be executed by new) : + arrow function
Prototype This Function + es6 quick created functions (QF functions) + built-in functions such as push, pop, etcCopy the code
The function is a first-class citizen
- Key points:
Fuction is an instance of Function itself
- Pay attention to
- Take object.hasownProperty for example (this is a property on Object.prototype).
- Search mechanism:
Object.hasOwnProperty === Object.–proto__.__proto–.hasOwnProperty
Object.hasOwnProperty === Object.prototype.hasOwnProperty
(4) Summary
5, small topic
function Foo() {
getName = function () {
console.log(1);
};
return this;
}
Foo.getName = function () {
console.log(2);
};
Foo.prototype.getName = function () {
console.log(3);
};
var getName = function () {
console.log(4);
};
function getName() {
console.log(5);
}
Foo.getName();
getName();
Foo().getName();
getName();
new Foo.getName();
new Foo().getName();
new new Foo().getName();
Copy the code