preface
Hello, everyone, I am zha 👦, a little hard every day 💪, can be promoted and pay 💰 when the general manager as CEO married Bai Fumei to the peak of their life 🗻, think there is still a little excitement.
This is my ✍ article # 13, hoping to ✍ everything clear. (Of course, if you don’t know anything, use the comments section to help!) ⏰, start the clock!
If you find this article helpful, please like, bookmark, comment, leave your learning footprints 👣, I’d love to talk about 😃
No more words, start learning!!
I will continue to revise the content of this article, let’s discuss! 😁
Learn CSS layout 🤣
Each element has a default display value, depending on the type of the element. The default value for most elements is either block or inline.
- Each element has a default display
Block elements are called block-level elements; An inline element is called an inline element
The common display value, sometimes none, is used to hide or display elements without deleting them. Display: None.
The display element set to None does not take up the space it should display; Use visibility: Hidden occupies the space but is hidden while the element remains.
Position property: static is the default value. Fixed, a fixed position element that is positioned relative to the window and remains in the same position even as the page scrolls.
Float in the CSS property, float can implement text around the image:
img {
float: right;
margin: 0 0 1em 1em;
}
Copy the code
The clear property can be used for controlled float elements. If a box has float: left, use clear: left to see how the element floats to the left.
Clear float, ClearFix hack, can use new CSS styles:
.clearfix {
overflow: auto;
}
Copy the code
Percentage width. Percentage is a unit of measurement relative to the contained block.
.clearfix {
float: right;
width: 50%;
}
nav {
float: left;
width: 15%;
}
section {
margin-left: 15%;
}
Copy the code
Responsive design is a strategy to “render” a website differently for different browsers and devices, making it look good in different situations.
Inline-block is an inline block label
.box {
float: left;
width: 200px;
height: 100px;
margin: 1em;
}
.after-box {
clear: left; } // Same effect.box1 {
display: inline-block;
width: 200px;
height: 100px;
margin: 1em;
}
Copy the code
Flexbox is a new layout mode for CSS3 designed to meet the complex needs of the modern Web.
<div class="flex-container">
<div class="flex-item">flex item 1</div>
<div class="flex-item">flex item 2</div>
</div>
.flex-container {
display: -webkit-flex;
display: flex;
width: 300px;
height: 240px;
background-color: Silver;
}
.flex-item {
background-color: DeepSkyBlue;
width: 100px;
height: 100px;
margin: 5px;
}
Copy the code
JavaScript variable 😊
1, Int 2, Float 3, Boolean 4, String 5, Array 6, Object 7, Function 8, Regular Expression Regular Expression
Hump nomenclature 😀
- All lowercase words are underlined
- Mixed case, big hump, uppercase for each word, small hump, lowercase for the first word, uppercase for the other letters.
Rules 😁
The first character, letter or underscore; Composition, English letters, numbers, underscores; (Disabled, JavaScript keywords and reserved words)
The statement 😃
Display declaration, using var variable name, ({no type, duplicate declaration, implicit declaration, direct copy without declaration}), ({declare first, read and write after, assign first, calculate after}).
Variable type 😃
Value type, occupy a fixed space, stored in the stack, save and copy is the value itself, use typeof detection data type, basic type data is the value type.
The reference type is stored in the heap, a pointer to the object is saved and copied, the type of the data is checked with instanceof, and the object constructed with the new() method is a reference.
Scope 😄
Global variables, including variables defined outside the function body, variables defined inside the function body without var; Call, at any location.
Local variables, including variables declared inside functions using var, parameter variables of functions; Call, inside the current function body.
Priority, local variable is higher than global variable of the same name, parameter variable is higher than global variable of the same name, local variable is higher than parameter variable of the same name.
Properties: block-level scopes are ignored. Global variables are properties of the global object and local variables are properties of the calling object.
Scope chain, the inner function can access the outer function local variables, the outer function cannot access the inner function local variables.
Declaration cycle: global variables are declared until they are deleted, and local variables are declared until the function is finished or shown to be deleted. Recycle mechanism, clear labeling, reference counting.
The logical operator 😅
! Logic is not
Returns true
An empty string0
null
NaN
undefined
Copy the code
Returns false
Object not empty string not0Numerical (Infinity)Copy the code
Note: Logical non, used twice in a row, can convert any type to a Boolean value
&& logic with 😆
- Returns the second operand when the first operand is an object
- Return object if the second operand is an object and the first operand is true
- Both operands are objects and return the second operand
- If an operand is null, null is returned
- NaN is returned when an operand is NaN
- An operand of undefined returns undefined
Note: When the value of the first operand is false, the second operand is not evaluated.
Logic or | | 😉
- The first operand is the object that returns the first operand
- The first operand is false and returns the second operand
- Both operands are objects and return the first operand
- Both operands are NULL, and null is returned
- Both operands are NaN and return NaN
- Both operands are undefined, return undefined
Note: If the first operand is true, the second operand is not evaluated.
JavaScript array
add
Push () adds the array to the end of the array. Unshift () adds the element concat() to the head of the array to merge the two arrays
delete
Pop () removes and returns the last element of the numeric value shift() removes and returns the first element of the array
Queue method (fifO); Stack method (last in first out).
Splice () and slice ()
splice()
- Delete any number of items: 1, the starting index to delete, 2, the number of items to delete
- Inserts the specified item at the specified position: 1, starting subscript, 2,0 (without deleting any item), 3, the item to insert.
- Replace any number of items: 1, starting index, 2, number of items to delete, 3, items to insert
The splice() method, annotated, changes the original array. Use to add or remove elements from an array.
arrayObject.splice(index,howmany,item1,..... ,itemX)var arr = ['a'.'b'.'c']
arr.splice(2.1) // Delete an array of deleted elements
['c']
arr.splice(2.0) // Delete 0, return an empty array
[]
var array = [1.2.3.4.5];
array.splice(3.2);
console.log(array);
// result: [1,2,3]
var myFish = ['angel'.'clown'.'mandarin'.'sturgeon'];
var removed = myFish.splice(2);
// Remove all elements from bit 2
// myFish: ["angel", "Clown "]
// Deleted element: ["mandarin", "sturgeon"]
Copy the code
All major browsers support Splice ()
Array Splice (), which deletes, inserts, and replaces arrays
Insert usage
Grammar: array splice (force,0And the value1And the value2...) ;// Indicates where to insert, 0 means to delete 0 elements, because insert and replace are extended by delete, value 1, value 2, the value to insert
var array = [1.2.3.4.5];
array.splice(2.0.11.22);
[1,2,11,22,3,4,5]
Copy the code
The use of substitution
Grammar: array splice (force, n, value1And the value2);
var array = [1.2.3.4.5];
array.splice(2.2.11.22);
[1,2,11,22,5]
Copy the code
The slice() function takes elements from an existing array to form a new array
- Returns the starting position of the item
- Returns the end position of the item
Property, if it is negative, the array length plus the value is used to determine the position. The revelation position is the actual index of the array, and the actual index of the end position is the end value minus 1.
Array.prototype.slice()
The slice() method returns a new array object. The original array will not be changed. This object is a shallow copy of the array determined by begin and end.
Praise:
const animals = ['1', '2', '3', '4', '5'];
console.log(animals.slice(2));
// expected output: Array ["3", "4", "5"]
console.log(animals.slice(2, 4));
// expected output: Array ["3", "4"]
console.log(animals.slice(1, 5));
// expected output: Array ["2", "3", "4", "5"]
Copy the code
Slice (start,end), truncated from start to end without end, returns a collection of truncated elements (only a shallow copy of the original elements to be given to the new array)
var fruits = ['a'.'b'.'c'.'d'.'e'];
var citrus = fruits.slice(1.3);
// fruits contains ['a', 'b', 'c', 'd', 'e']
// citrus contains ['b','c']
Copy the code
The Slice method converts an array-like object/collection to a new array.
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1.2.3); / / [1, 2, 3]
Copy the code
In JavaScript, almost everything is an object, except immutable primitive values like String, number, and Booleans.
Array.prototype.slice
function myFunc() {
Arguments is a class array object, not a real array
arguments.sort();
// Borrow the method slice from the Array prototype
// It takes an array-like object (key:value)
// Return a real array
var args = Array.prototype.slice.call(arguments);
// Args is now a real Array, so you can use the sort() method of Array
args.sort();
}
Copy the code
Array sort, reverse() reverses the order of elements in an array, and sort() sorts an array of characters or numbers.
function compare(value1, value2) {
if(value1 < value2) {
return -1;
}else if(value1 > value2) {
return 1;
}else{
return 0; }}Copy the code
An array of conversion
- ToString () is converted to a string and returned
- ToLocaleString () converts to a local format string and returns
- Join () splits the array with the specified separator and converts it to a string
The toString() function returns the current object as a string. This method belongs to Object.
Iterative method: parameters
- Every returns true if the function returns true for each item
- Filter returns all array members whose value is true
- ForEach has no return value
- Map returns an array of the results of each function call
- Return true if any of the items in some return true
Receiving parameters:
- The function to run on each term
- The scope object that runs the function
Passing in parameters:
- The value of the array item
- Index is the position of the item in the array
- The array object itself is array
Reduction method:
- Reduce traverses from the start bit of the array
- ReduceRight iterates from the end of the array
The reduce() method takes a function as an accumulator, and each value in the array (from left to right) starts to shrink and eventually evaluates to a value.
Reduce () can be used as a higher-order function for compose of functions.
Note: Reduce () does not perform a callback for an empty array.
var numbers = [1.2.3.4]; Numbers. Reduce (callback function);Copy the code
const array1 = [1.2.3.4];
const reducer = (accumulator, currentValue) = > accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// 15
var arr = [1.2.3.4];
/ / sum
var sum = arr.reduce((x,y) = >x+y)
var sum1 = arr.reduce((x,y) = >x*y)
Copy the code
Find the maximum value of an array item
var max = arr.reduce(function (prev, cur) {
return Math.max(prev,cur);
});
Copy the code
Take the maximum of two values and continue to enter the next cycle.
Array to heavy
arr.reduce(function(prev,cur,index,arr){... }, init); Arr stands for primitive array; Prev represents the return value from the last call to the callback, or the initial value init; Cur represents the array element currently being processed; Index represents the index of the array element being processed, or if init is provided0Otherwise, the index is1; Init represents the initial value. Arr. Reduce (callback,[initialValue]) initialValue (as the first parameter to call callback for the first time.Copy the code
If this array is empty, what happens when you apply reduce?
var arr = [];
var sum = arr.reduce(function(prev, cur, index, arr) {
console.log(prev, cur, index);
return prev + cur;
})
TypeError: Reduce of empty array with no initial value
var arr = [];
var sum = arr.reduce(function(prev, cur, index, arr) {
console.log(prev, cur, index);
returnprev + cur; },0)
console.log(arr, sum); / / [] 0
Copy the code
Js in, generally used to iterate over objects, can also be used to iterate over groups of numbers
The in function checks whether the property exists in the object, true or false.
In determines the array, and the index number is the property.
For an array it loops out the elements of the array; For objects, the loop out is object properties; When ‘object’ is an array: ‘variable’ refers to the ‘index’ of the array; When ‘object’ is an object, ‘variable’ refers to the ‘property’ of the object.
Count the number of occurrences of each element in the array
Var scoreReport = [{name: 'dada', score: 100}, {name: 'nezha ', score: 100} 99 } ] // for var sum = 0 for(var i = 0; i<scoreReport.length; i++) { sum += scoreReport[i].score }Copy the code
If you use reduce
var sum = scoreReport.reduce(function(prev, cur) {
return cur.score + prev
},0);
Copy the code
Vuex
In Vuex, data in state can only be modified in mutations, while state cannot be directly modified in Actions
Create an instance of vuex. Store and save it in the Store variable. Export Store using export Default
import Vuex from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
})
export default store
Copy the code
state
Frequently written file store.js
import Vue from 'vue' import Vuex from 'vuex' // import * as getters from './getters' Vue.use(Vuex) const state = { // Place the initial state a: 123}; Const mutations = {// place our state change function}; export default new Vuex.Store({ state, mutations, // getters })Copy the code
This.$store.state to retrieve the defined data
import Vuex from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 1}})export default store
Copy the code
import Vuex from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 1
},
getters: {
// Getters is equivalent to computed property in VUE
getStateCount: function(state){
return state.count+1; }}})export default store
Copy the code
To change the value in state, you need to commit mutation to change it
Getters in Vuex, like computed properties, return values of getters are cached based on their dependencies and recalculated only if their dependencies change.
The Getter accepts state as its first argument:
const store = new Vuex.Store({
state: {
todos: [{id: 1.text: '... '.done: true },
{ id: 2.text: '... '.done: false}},getters: {
doneTodos: state= > {
return state.todos.filter(todo= > todo.done)
}
}
})
Copy the code
When the getter is accessed through a property, it’s cached as part of the Vue’s responsive system where the getter is called every time it’s accessed through a method, it doesn’t cache the result.
In a function {this.$store.commit('add');
}
import Vuex from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 1
},
getters: {
// Getters is equivalent to computed property in VUE
getStateCount: function(state){
return state.count+1; }},mutations: {
add(state) {
state.count += 1; }}})export default store
// xxx.vue
{{$store.getters.getStateCount}}
Copy the code
Commit mutation- an object-style commit that uses an object containing the type attribute directly:
store.commit({
type: 'increment'.amount: 10
})
Copy the code
Vuex also has an Actions, which is designed to change the status value in the Store by submitting an Actions, and then submitting mutations in the Actions.
Define the function for actions and submit mutations first
Example:
In a function {this.$store.dispatch('addFun')}import Vuex from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 1
},
getters: {
// Getters is equivalent to computed property in VUE
getStateCount: function(state){
return state.count+1; }},mutations: {
add(state) {
state.count += 1; }},actions: {
// Register actions, equivalent to methods in Vue
addFun(context){
// Context receives a context object with the same method attributes as the store instance
context.commit('add')}}})export default store
Copy the code
Use mapState, mapGetters, mapActions instead of this.$store.state.count and this.$store.dispatch(‘addFun’).
How to use:
import {mapState, mapGetters, mapActions} from 'vuex';
// Use computed state changescomputed: { ... mapState({countdada: state= >state.count
})
}
// Map the getters in store to local computed properties:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// Mix getters into a computed object using the object expansion operator. mapGetters(['doneTodosCount'.'anotherGetter'.// ...])}}... mapGetters({/ / the ` enclosing doneCount ` mapping for ` enclosing $store. Getters. DoneTodosCount `
doneCount: 'doneTodosCount'
})
Copy the code
JavaScript in this
What is this, that, this keyword ThisBinding executed for the current environment.
In most cases, how the function is called determines the value of this. The this pointer is determined at call time, not creation time.
// this points to the global variable
function dadaqianduan() {
return this;
}
console.log(dadaqianduan() === window); // true
Copy the code
Use call(), apply(), and this to point to the bound object.
var person = {
name: 'dada'.age: 12
};
function sayHello(job) {
console.log(this.name + "," + this.age + "," + job);
}
sayHello.call(person, 'it'); // dada,12,it
sayHello.apply(person, ['it']);
Copy the code
Arrow functions, all arrow functions don’t have their own this and point to the outer layer. The arrow function captures the this value of its context as its own. (Inside a function, the value of this depends on how the function is called)
The arrow function’s this always points to the object at which it was defined. Is not the object on which the runtime resides.
function da() {
setTimeout(() = >{
console.log('this'.this.id)
},1000);
}
da.call({id: 12});
Copy the code
The arrow function is inside the da function, and only after the da function is run will it generate, by definition, the object on which the so, da runs, which happens to be the object on which the arrow function was defined.
Using this in an arrow function is just like using a normal variable. Searching within the scope of an arrow function does not always refer to the parent scope.
This again refers to the global variable as follows:
Thanks to nuggets:
var name = 'da';
var person = {
name: 'dadaqianduan'.fun: function() {
return this.name; }}var getName = person.getName();
console.log(getName()); // da
/ / to
var name = 'da';
var person = {
name: 'dadaqianduan'.getName: function() {
return this.name; }}var fun = person.getName;
console.log(fun()); // da
Copy the code
As a constructor, this is bound to the new object being constructed.
function Person(name) {
this.name = name;
this.age = 12;
this.say = function() {
console.log(this.name + ":" + this.age);
}
}
var pserson = new Person('dadaqianduan');
person.say();
Copy the code
This can be called in several scenarios:
var obj = {
a: 1.b: function() {
console.log(this); }}Copy the code
- When called as an object, point to the object obj.b(); / / points to obj
- When called as a function, var b = obj.b; b(); // point to the global window
- When called as a constructor, var b = new Fun(); // this. Points to the current instance object
- When called as call and apply, obj.b.ply (object, []); // This refers to the current object
Example:
var a = dadaqianduan;
var obj = {
a: dada
}
function fun() {
console.log(this.a);
}
fun(); // dadaqianduan
fun.call(obj); // dada
Copy the code
function da(a,b,c) {
console.log(arguments);
// Use call/apply to convert arguments to an array and return the result as an array
var arg = [].slice.call(arguments);
}
da(1.2.3)
Copy the code
Global context, non-strict mode and strict mode where this refers to the top-level object.
this= = =window // true
Copy the code
Function context
var name = 'dadaqianduan';
var fun = function() {
console.log(this.name);
}
fun(); // 'dadaqianduan'
Copy the code
The call() method calls a function with a specified this value and one or more arguments given separately.
The syntax and actions of this method are similar to those of apply(), except that call() accepts a list of arguments, while apply() accepts an array of arguments.
Example:
function da(name, age) {
this.name = name;
this.age = age;
}
function dada(name, age) {
da.call(this, name, age);
this.job = 'it';
}
console.log(new dada('dadaqianduan, 12').name);
// dadaqianduan
Copy the code
Grammar:
function.call(thisArg, arg1, arg2, ...)
Copy the code
Argument :thisArg, this value used when function is run, this may not be the actual value seen by the method. arg1,arg2,… Specifies the argument list.
The return value of the function called with the this value and arguments provided by the caller. If the method returns no value, undefined is returned.
Description:
Call () allows different objects to assign and call functions/methods belonging to one object. Provides a new this value for the currently called function/method. You can use call to implement inheritance.
Call the parent constructor using the call method
function Person(name, age) {
this.name = name;
this.age = age;
}
function Child1(name, age) {
Person.call(this, name, age);
this.eat = 'beff';
}
function Child2(name, age) {
Person.call(this, name, age);
this.eat = 'food';
}
var da1 = new Child1('Nezha 1'.12);
var da2 = new Child2('Nezha 2'.12);
Copy the code
Call anonymous functions using the call method
var person = [
{
name: 'da1'.age: 1
},
{
name: 'da2'.age: 2}];for(var i=0; i<person.length; i++) {
(function(i){
this.fun = function() {
console.log('dadaqianduan');
}
this.fun();
}).call(person[i], i);
}
Copy the code
class Person{
constructor(name) {
this.name = name;
}
fun(){
console.log(this.name); }}let da = new Person('Dada front end');
da.fun(); // Dada front-end
Copy the code
For arrow function calls, which does not have this, super, the arguments, new. The target binding, can’t use the new call, no prototype object, you can’t change this binding, parameter name cannot be repeated.
This is bound to the newly created object via a new call, a return function or object that returns not the newly created object, but an explicit return function or object; Calls to call or apply, in non-strict mode, null and undefined; Object, bound to that object; Normal function calls, strictly mode, undefined.
Note: You can also remember this as an object, methods (functions) as an object, and ordinary functions.
For binding examples, in non-strict mode this refers to a global object, in strict mode this is bound to undefined, in implicit binding, the way obj.foo() is called, and this in foo refers to obj.
The call() or apply() methods directly specify the binding object for this, and the arrow function for this points to the outer scope.
Example:
var a = "dadaqianduan";
function foo () {
console.log(this.a)
}
foo();
window.a = "dadaqianduan";
function foo() {
console.log(this.a)
}
window.foo();
// dadaqianduan
Copy the code
Strict mode only makes this point to undefined within a function, but does not change the global this point. Only var binds variables to the window; let and const do not.
let a = "dada"
const b = "dada1"
function foo () {
console.log(this.a)
console.log(this.b)
}
foo();
console.log(window.a)
// undefined
// undefined
// undefined
Copy the code
var a = "da";
function fun() {
var a = "da1";
console.log(this); // window
console.log(this.a); // so, window.a -> da
}
fun(); // Window calls fun
Copy the code
var a = "da";
function fun() {
// This points to window
var a = "da1";
function inner() {
console.log(this.a);
}
inner();
}
fun(); // da
Copy the code
Who calls the function last? This in the function refers to the nearest principle
Example:
function fun() {
console.log(this.a)
}
var obj = {
a: 'da',
fun
}
var a = 'da1';
obj.fun(); // da
// var obj = {fun} => var obj = {fun: fun}Obj refers to fun() and assigns to obj. Fun calls obj and prints the a in objvar obj = {
a: 'da'.fun: function() {
// this points to obj
console.log(this.a)
}
}
var a = 'da1'
obj.fun()
Copy the code
function fun() {
console.log(this.a);
};
var obj = {
a: 'da',
fun
};
var a = 'da1';
var fun1 = obj.fun;
obj.fun(); // this is obj -> da
fun1(); / / points to obj. Fun (); So, this refers to window
// window.fun1()
Copy the code
function fun() {
console.log(this.a);
};
var obj = {
a: 'da',
fun
};
var a = 'da1';
var fun1 = obj.fun;
var ojb1 = {
a: 'da2'.fun2: obj.fun
};
obj.fun(); // this is obj -> da
fun1(); // obj.fun() -> the caller is window, so this points to window, -> da1
obj1.fun2(); // the caller is obj1, so this points to obj1
Copy the code
function fun() {
console.log(this.a);
};
function doFun(fn) {
console.log(this);
fn();
};
var obj = {
a: 'da',
fun
};
var a = 'da1';
doFun(obj.fun); // obj.fun(); So, inside this refers to window -> da1
Copy the code
function fun() {
console.log(this.a);
};
function doFun(fn) {
console.log(this);
fn();
};
var obj = {
a: 'da',
fun
}
var a = 'da1';
var obj1 = {
a: 'da2',
doFun
};
obj1.doFun(obj.fun) // Obj1 calls doFun(), passing obj.fun, this pointing to obj1.
// obj.fun() prints da1Reason: Passing a function as an argument to another function causes implicit loss, called callback lossthisBinding.// In strict mode, undefined is bound
Copy the code
call,apply,bind
While functions that use call and apply are executed directly, bind creates a new function that needs to be called manually.
Example:
function fun() {
console.log(this.a);
};
var obj = {
a: 'da'
};
var a = 'da1';
fun(); // da1
fun.call(obj); // da
fun.apply(obj); // da
fun.bind(obj); // Use bind to create a new function that will not be executed
Copy the code
Example:
If call,apply,bind receive parameters are empty ornull.undefinedWill ignore this parameterfunction fun() {
console.log(this.a);
};
var a = 'da';
fun.call(); // da
fun.call(null); // da
fun.call(undefined); // da
Copy the code
var ojb1 = {
a: 'da'
};
var obj2 = {
a: 'da1'.fun1: function() {
console.log(this.a); // da1
},
fun2: function() {
setTimeout(function(){
console.log(this); // window
console.log(this.a); // window.a -> da2
},0)}}var a = 'da2';
obj2.fun1(); // da1
obj2.fun2(); //
Copy the code
var obj1 = {
a: 'da'
};
var obj2 = {
a: 'da1'.fun1: function() {
console.log(this.a); // da1
},
fun2: function() {
setTimeout(function() {
console.log(this); / / so, {a: 'da'}
console.log(this.a); / / so, da
}.call(obj1), 0) // Bind the external object obj1}}var a = 'da2';
obj2.fun1();
obj2.fun2();
// Use obj2.fun2.call(obj1) to change the reference to this in fun2
Copy the code
var obj1 = {
a: 'da'
};
var obj2 = {
a: 'da1'.fun1: function() {
console.log(this.a); // da1
},
fun2: function() {
function inner() {
console.log(this); // window{... }
console.log(this.a); // da2} inner(); }}var a = 'da2';
obj2.fun1();
obj2.fun2();
Copy the code
function fun() {
console.log(this.a);
};
var obj = {
a: 'da'
};
var a = 'da1';
fun(); // da1
fun.call(obj); // da
fun().call(obj); Fun () -> da1; call(obj) will return an error
// fun() returns undefined -> returns fun. call()
Copy the code
function fun() {
console.log(this.a);
return function() {
console.log(this.a); }};var obj = {
a: 'da'
};
var a = 'da1';
fun(); // da1 -> returns an anonymous function that is not called. Fun ()() can be used; Calling anonymous Functions
fun.call(obj); // da -> returns an anonymous function, not called
fun().call(obj); // fun(), result da1, returns an anonymous function, and binds this to obj, this.a is obj.a -> result is da
// fun().call(obj); -> da1,da
Copy the code
Bind simply returns a new function
Example:
function fun() {
console.log(this.a);
return function() {
console.log(this.a); }}var obj = {
a: 'da'
};
var a = 'da1';
fun(); // da1
fun.bind(obj); // does not execute, returns a new function
fun().bind(obj); // da1 -> anonymous function binding obj, not called.
Copy the code
function fun() {
console.log(this.a);
return function() {
console.log(this.a); }}var obj = {
a: 'da'
};
var a = 'da1';
fun.call(obj)(); // da , da1
// Fun is bound to obj,this refers to obj, anonymous function call
Copy the code
var obj = {
a: 'da'.fun: function() {
console.log(this.a);
return function() {
console.log(this.a)
}
}
};
var a = 'da1';
var obj1 = {
a: 'da2'
};
obj.fun()(); // this. A ->window
obj.fun.call(obj1)(); // bind obj1, the anonymous function returns ->window
obj.fun().call(obj1); // da1, bind obj1, so, this to obj2
Copy the code
var da1 = {
name: 'Nezha'.sayHello: function(age) {
console.log(this.name + age); }};var da2 = {
name: 'Dada front end'}; da1.sayHello(12);
// apply,call
da1.sayHello.apply(da2, [12]); // Dada front-end 12
da1.sayHello.call(da2, 12); // Dada front-end 12
Copy the code
simulationFunction.prototype.applyFun = function(context) {
context.fn = this;
context.fn();
// Remove function references from context
delete context.fn;
}
/ / parameters
Function.prototype.applyFun = function(context) {
context.fn = this;
var args = arguments[1];
context.fn(args.join(', ')); // join -> string
// Execute this function with ES6... Operator expands arG
// context.fn(... args);
delete context.fn;
}
Copy the code
var a = 'da';
function sayHello() {
console.log(this.name);
}
sayHello.apply(null); // If null is passed or no argument is passed, it refers to window
var a = 'da';
function sayHello() {
console.log(this.name);
}
sayHello.apply(); // If null is passed or no argument is passed, it refers to window
Copy the code
Override properties, ES5:
var a = {
name: 'da'
};
a.name = 'da1'
Copy the code
Es6 introduces a primitive data type,Symbol, which represents a unique value. The Symbol function can accept a string as an argument. The Symbol function cannot use the new command. The generated Symbol is a primitive value, not an object.
Example:
var s1 = Symbol(a);var s2 = Symbol(a); s1 === s2// false
var s1 = Symbol("foo");
var s2 = Symbol("foo");
s1 === s2 // false
Copy the code
When the Symbol value is used as an object attribute name, the dot operator is not used.
Example:
var mySymbol = Symbol(a);// The first way
var a = {};
a[mySymbol] = 'Nezha';
// The second way
var a = {
[mySymbol]: 'Nezha'
};
// The third way
var a = {};
Object.defineProperty(a, mySymbol, { value: 'Nezha' });
// All the above methods give the same result
a[mySymbol] // "Nezha"
Copy the code
var a = {};
var name = Symbol(a); a.name ='da1';
a[name] = 'da2';
console.log(a.name,a[name]); //da1,da2
Copy the code
var obj = {
a: 'da'.fun: function(b) {
b = b || this.a
return function (c) {
console.log(this.a + b + c)
}
}
}
var a = 'da1';
var obj1 = {
a: 'da2'
}
obj.fun(a).call(obj1, 1)
// obj. Fun (da1) -> da1; call changes this; ojb1; so; this.
// Final result,da2 da1 1
obj.fun.call(obj1)(1)
// Obj1 is the object of the fun this binding in obj. This refers to Obj1
/ / obj. Fun. Call (obj1) without passing parameters, so, because of b = b | | this. A
// so, b is (remember to bind obj1)da2. Finally, an anonymous function is called, in which this points to the window
// da1(this.a refers to window),da2,1
Copy the code
function fun1 () {
console.log(this.a);
};
var a = 'da';
var obj = {
a: 'da1'
}
var fun2 = function() {
fun1.call(obj);
};
fun2(); // da1
fun2.call(window); // da1
Copy the code
function fun1(b) {
console.log(`The ${this.a} + ${b}`)
return this.a + b
}
var a = 1
var obj = {
a: 3
}
var fun2 = function () {
returnfun1.call(obj, ... arguments) }var dada = fun2(5)
console.log(dada)
'3 + 5'
8
// fun2(5)-> fun1; obj, so, this.a = obj
Copy the code
function fun(item) {
console.log(item, this.a);
};
var obj = {
a: 'Nezha'
};
var a = 'dada'
var arr = [1.2.3];
// the second parameter of forEach, map, filter can be bound to this
arr.filter(function(i){
console.log(i, this.a);
return i>2
},obj)
1 'Nezha'
2 'Nezha'
3 'Nezha'
Copy the code
function da (name) {
this.name = name
};
var name = 'da1';
var dada = new da('da2');
console.log(dada.name) // da2
// new calls da and constructs a new object dada, which is bound to this in da
Copy the code
var name = 'Nezha';
function fun (name) { // constructor
this.name = name;
this.daFun = function () {
console.log(this.name);
return function () {
console.log(this.name); }}}var da1 = new fun('Nezha 1');
var da2 = new fun('Nezha 2');
da1.daFun.call(da2)()
da1.daFun().call(da2)
Copy the code
2. To change one’s mind:
var name = 'Nezha';
Var da1 = new fun(' Zha 1');
var da1 = {
name: 'Nezha 1'.daFun: function() {
console.log(this.name);
return function () {
console.log(this.name); }}}Var da2 = new fun(' Nezha 2');
var da2 = {
name: 'Nezha 2'.daFun: function() {
console.log(this.name);
return function () {
console.log(this.name);
}
}
}
da1.daFun.call(da2)() // The daFun function binds to da2 and refers to da2, so, this refers to da2, outputs Nezha 2, and finally calls (). The internal anonymous function is called by window to print Nezha
// Nezha
da1.daFun().call(da2)
// da1.dafun ().call(da2) binds this of the anonymous function to da2
// da1.dafun () -> Nezha 1 -> Nezha 2
Copy the code
Arrow function
This in the arrow function, determined by the outer scope, refers to this when the function is defined, not when it is executed. (discuss)
var obj = {
name: 'Nezha'.fun1: () = > {
// This refers to the outer scope. This refers to the function definition, which is window
console.log(this.name)
},
fun2: function() {
console.log(this.name)
return () = > {
console.log(this.name); }}}var name = 'Dada front end';
obj.fun1(); // this. Name -> this
obj.fun2()(); // this.name, this.name(anonymous function)
Obj.fun2 ()() obj.fun2()()
// The first pointer to the object that calls it, obj, so, is nezha. The anonymous function inside is the arrow function. When the arrow function points to the definition, it is the outer scope of this that determines this. He is also nezha.
Copy the code
var name = 'Dada front end';
var obj1 = {
name: 'Nezha 1'.fun: function() {
console.log(this.name)
}
}
var obj2 = {
name: 'Nezha 2'.fun: () = > {
console.log(this.name)
}
}
obj1.fun() // From obj1, so, Nezha 1
obj2.fun() // This is defined to refer to the front end of the window, so, and dada
Copy the code
var name = 'Dada front end';
var obj1 = {
name: 'Nezha 1'.fun: function () {
console.log(this.name);
return function() {
console.log(this.name);
}
}
}
obj1.fun()();
// obj1.fun() -> nezha; // obj1.fun() -> Nezha
// Nezha, nezha
var obj2 = {
name: 'Nezha 2'.fun: function() {
console.log(this.name);
return () = > {
console.log(this.name);
}
}
}
obj2.fun()(); // obj2.fun() the first value is nezha 2, and the second arrow function, this, refers to the outer layer, is obj2's this, so, is Nezha 2
// Nezha 2, Nezha 2
var obj3 = {
name: 'Nezha 3'.fun: () = > {
console.log(this.name);
return function() {
console.log(this.name)
}
}
}
obj3.fun()(); // Dadda front-end, dadda front-end
// The first this.name arrow function is defined by the outer scope and refers to the window. The memory function is defined by the caller.
var obj4 = {
name: 'Nezha 4'.fun: () = > {
console.log(this.name);
return () = > {
console.log(this.name);
}
}
}
obj4.fun()(); // Dada front, dada front, define time, not call time
Copy the code
var name = 'Dada front end';
function dada (name) {
this.name = name;
this.fun1 = function() {
console.log(this.name);
}
this.fun2 = () = > {
// point to the outer scope function dada
console.log(this.name); }}var da2 = {
name: 'da2'.fun2: () = > {
console.log(this.name); }}var da1 = new dada('Nezha');
da1.fun1(); // Nezha is a normal function whose caller is dada (determined by the last caller).
da1.fun2(); // The arrow function is defined by the outer scope
// The outer scope is the function dada, constructor, new to generate object da1, which points to dada
da2.fun2(); // The scope of da2 is under window, so this points to window
Copy the code
var name = 'Dada front end'.function dada(name) {
this.name = name;
this.fun1 = function() { // A normal function
console.log(this.name); / / dada
return function() { // Anonymous function
console.log(this.name); // Dada front-end}}this.fun2 = function() { // A normal function
console.log(this.name); / / dada
return () = > { // Arrow function
console.log(this.name); // Depending on the outer layer, the outer layer is the dada function with a value of dada}}this.fun3 = () = > { // Arrow function
console.log(this.name); // Dada, so, dada
return function() { // A normal function
console.log(this.name) // At the caller's discretion, da1.foo3() returns a normal function with the outer literal da1 in the window, so, at the front end of the window}}this.fun4 = () = > { // Arrow function
console.log(this.name); // When defined, this refers to the outer layer, dada
return () = > { // Arrow function
console.log(this.name); // Point to the outer layer, dada}}}var da1 = new dada('达达');
da1.fun1()(); // Dada dada front-end
da1.fun2()(); // Dada dada
da1.fun3()(); // Dada dada front-end
da1.fun4()(); // Dada dada
Copy the code
The arrow function “this” cannot be changed directly by using bind, call, and apply; it can be changed by changing the direction of this in the scope.
Example:
var name = 'Dada front end';
var obj1 = {
name: Dada '1'.fun1: function() { // A normal function
console.log(this.name);
return () = > { // Arrow function
console.log(this.name); }},fun2: () = > {
// Arrow function
console.log(this.name);
return function() {
// A normal function
console.log(this.name); }}}var obj2 = {
name: Dada '2'
};
obj1.fun1.call(obj2)() //.call binds the object obj2, the first () run, dada 2, the second (), the arrow function, same as this, so dada 2 in the outer fun1 normal function
// Dada 2 dada 2
obj1.fun1().call(obj2) // The first call to obj1, dada1, returns the arrow function, the.call binding object obj2, tries to change this to refer to obj2, but does not work, because it is defined when this is executed, obj1, so, output dada1
// Dada 1 dada 1
obj1.fun2.call(obj2)() // obj1 literal,.call binding to obj2 is invalid, the first is arrow function, outer scope window, dada front, dada front, obj1.fun2.call(obj2) points to outer window
// Dada front-end
obj1.fun2().call(obj2) // Layer 1, arrow function, layer 2, ordinary function, layer 1 is directly the outer scope window, the front end of the dada
// The second layer is bound to obj2, so, dada 2
// Dda front-end, dda 2
Copy the code
Note: the literal creates an object whose scope is window. If it is an arrow function, this points to window
Example:
var name = 'Dada front end';
var da1 = {
name: 'dada1'.fun1: function() { // A normal function
console.log(this.name);
},
fun2: () = > console.log(this.name); // Arrow function
fun3: function() { // A normal function
return function() { // Anonymous function, ordinary function
console.log(this.name); }},fun4: function() { // A normal function
return () = > { // Arrow function
console.log(this.name); }}}var da2 = {
name: 'dada2'
};
da1.fun1(); // the literal da1, ordinary function, caller da1, so, points to da1, dada1
// dada1
da1.fun1.call(da2); // this.name is bound to da2,so, dadA2 via.call
// dada2
da1.fun2(); // Arrow function pointing to the front end of window, so, dada
// Dada front-end
da1.fun2.call(da2); //.call tries to change direction, but fails
// Dada front-end
da1.fun3()(); // An anonymous function pointing to the front end of the window
da1.fun3.call(da2); // Returns an anonymous function pointing to the front end of the window
da1.fun3().call(da2); //
da1.fun3() // Bind da2 with.call, return this normal function, bind da2, so, dadA2
//
() {
console.log(this.name)
}
//
// dada2
//
function() { // A normal function
return function() { // Anonymous function, ordinary function
console.log(this.name); }},//
da1.fun4()(); // this refers to the definition, da1, so, dada1
// dada1
da1.fun4.call(da2)(); Function () {return arrow function}; // a function() {return arrow function}; The outer function is bound to refer to DA2, DADA2
// dada2
da1.fun4().call(da2); // When fun4() is defined, dada1 is returned in this.name
// dada1
Copy the code
var name = 'Dada front end';
function dada(name) {
this.name = name;
this.fun1 = function() {
console.log(this.name);
},
this.fun2 = () = > console.log(this.name),
this.fun3 = function() {
return function() {
console.log(this.name)}},this.fun4 = function() {
return () = > {
console.log(this.name)
}
}
}
var da1 = new dada('1');
var da2 = new dada('2');
da1.fun1(); // new is bound to dada, 1
da1.fun1.call(da2); // bind to da2, 2
da1.fun2(); // arrow function, outer dada,new dada bound dada, 1
da1.fun2.call(da2); //.call wants to change the direction of this, but not for arrow functions, 1
da1.fun3()(); // Return a normal function, this refers to the window, the front end
da1.fun3.call(da2)(); // Bind da2, but also point to window, the front end
da1.fun3().call(da2); // bind da2, return run (), bind da2, this points to da2, 2
// da1.fun3()
ƒ () {
console.log(this.name)
}
//
da1.fun4()(); // return arrow function, call da1, pointing to outer da1, 1
// da1.fun4();
/ / - > return
() = > {
console.log(this.name)
}
da1.fun4.call(da2)(); //.call() binds to da2, calls (), and changes the outer layer to da2, 2
da1.fun4().call(da2);
// da1.fun4();
/ / - > return
() = > {
console.log(this.name)
}
Da1, new dada('1') new object, so, 1
Copy the code
var name = 'Dada front end'
function Person (name) {
this.name = name
this.obj = {
name: 'obj'.fun1: function () {
return function () {
console.log(this.name)
}
},
fun2: function () {
return () = > {
console.log(this.name)
}
}
}
}
var da1 = new Person('1')
var da2 = new Person('2')
da1.obj.fun1()(); This refers to the outer window. This refers to the outer window
da1.obj.fun1.call(da2)(); // In da2, the anonymous function still refers to the outer window
da1.obj.fun1().call(da2); // 2, run fun1(), return anonymous function, bind da2, change this, so inside anonymous function to 2
da1.obj.fun2()(); // obj, return arrow function in the normal function, arrow function definition this points to obj, so return arrow function this.name is obj
da1.obj.fun2.call(da2)(); // 2 fun2, for function(){... }, the binding changes the first layer of this to refer to da2, so, 2
da1.obj.fun2().call(da2); // obj arrow function invalid, so, obj
Copy the code
function fun() {
console.log(this.a); // this.a outer window, da
};
var a = 'da';
(function(){
// This refers to the window. This is undefined under strict use mode
'use strict';
fun(); // normal function call // da
// this.fun(); This will result in an error}) ();Copy the code
This point
Example:
function dada() {
this.a = 'da'; // this points to window, window under window.a = 'da'
console.log(this.a); // window.a
}
dada(); // da
Copy the code
This in the function dada, determined when the function is called, refers to the environment in which the function is currently running
Example:
var a = 'da';
function da() {
console.log(this.a);
};
var obj = {
a: 'da1'.fun: da
};
obj.fun(); // da1
Copy the code
Object method call pointing to this object obj
Call simulation implementation
Example:
var obj = {
name: 'dada'
};
function fun() {
console.log(this.name); // window.name
};
fun.call(obj); // bind the object obj, dada
Copy the code
// Imagine a change
var obj = {
/ / object
name: 'dada'./ / property
fun: function() {
// A normal function
console.log(this.name); // obj.fun() - The object obj calls fun() dada}}Copy the code
Obj. fun = function (Assign a function)// Set the function as a property of the object
obj.fun()
deleteThe obj.fun propertyvar obj = {
name: 'dada'
};
function fun() {
console.log(this.name); // window.name
};
fun.call(obj); // bind the object obj, dada
Copy the code
Look at the way to write the following:
Function.prototype.myCall = function(An object context) {
context.fun = this; // This refers to the dada() function
context.fun();
delete context.fun;
}
var obj = {
name: 'dada'
};
function dada() {
console.log(this.name);
};
dada.myCall(obj); // obj, bind to this object,this, context.fun = this
Copy the code
// Simulate parameter transfer problem call
var obj = {
value: 'dada'
};
function fun(name, age) {
console.log(name)
console.log(age)
console.log(this.value);
}
fun.call(obj, 'da'.12);
// da
/ / 12
// dada
Copy the code
Arguments is an array-like object
Take a look atarguments
arguments = {
0: obj,
1: 'da'.2: 12.length: 3
}
Copy the code
The next step is to extract the parameter:
Call the original method, the calls are separate
The JavaScript eval () function
Definitions and Usage
The eval() function evaluates a JavaScript string and executes it as script code.
If the argument is an expression, the eval() function executes the expression. If the argument is a Javascript statement, eval() executes the Javascript statement.
eval(string)
Copy the code
Function.prototype.myCall = function(context) {
context.fun = this;
var args = [];
for(var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + '] ');
}
eval('context.fun(' + args +') ');
delete context.fun;
}
Copy the code
Note: The argument can be null
var name = 'dada';
function fun() {
console.log(this.name);
}
fun.call(null); // this points to window, dada
Copy the code
So change
Function.prototype.myCall = function (context) {
var context = context || window;
context.fun = this;
var args = [];
for(var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + '] ');
}
var result = eval('context.fun(' + args +') ');
delete context.fun
return result;
}
Copy the code
Apply simulation implementation
Example:
I pass in an object and an array code from @dig YubaFunction.prototype.apply = function (context, arr) {
var context = Object(context) || window;
context.fn = this;
var result;
if(! arr) { result = context.fn(); }else {
var args = [];
for (var i = 0, len = arr.length; i < len; i++) {
args.push('arr[' + i + '] ');
}
result = eval('context.fn(' + args + ') ')}delete context.fn
return result;
}
Copy the code
Bind simulation implementation
Bind: returns a function that can take arguments
Example:
var obj = {
name: 'da';
};
function fun() {
console.log(this.name);
}
// Return a function
var da1 = fun.bind(obj);
da1(); // da
Copy the code
The bind() method creates a new function, and when bind() is called, the new function’s this is referred to as the first argument to bind(), the binding object, and the remaining arguments will be arguments to the new function.
Bind redirects the function this, but instead of immediately executing the function, bind returns a new function bound to this.
Simulation implementation:
Simulation implementation step 1:
Function.prototype.myBind = function(context){
var that = this
return function(){
return that.apply(context)
}
}
/ / write 2
Function.prototype.bind_ = function (obj) {
var fn = this;
return function () {
fn.apply(obj);
};
};
Copy the code
Simulation implementation step 2: support function parameter passing
Function.prototype.myBind = function (context) {
var that = this; / / function
var args = Array.prototype.slice.call(arguments.1);
return function () {
var bindArgs = Array.prototype.slice.call(arguments);
returnthat.apply(context,args.concat(bindArgs)); }}/ / write 2
Function.prototype.bind_ = function (obj) {
// Bit 0 is this, so start with the first bit
var args = Array.prototype.slice.call(arguments.1);
var fn = this;
return function () {
fn.apply(obj, args);
};
};
Function.prototype.bind_ = function (obj) {
var args = Array.prototype.slice.call(arguments.1);
var fn = this;
return function () {
// Secondary call
var params = Array.prototype.slice.call(arguments);
fn.apply(obj, args.concat(params));
};
};
Copy the code
Added this judgment and stereotype inheritance
Function.prototype.bind_ = function (obj) {
var args = Array.prototype.slice.call(arguments.1);
var fn = this;
var instanceObj = function () {
var params = Array.prototype.slice.call(arguments);
// Call from constructor
// True this points to the instance, otherwise obj
fn.apply(this.constructor === fn ? this : obj, args.concat(params));
};
// Prototype chain inheritance
instanceObj.prototype = fn.prototype;
return instanceObj;
};
Copy the code
Simulation implementation modified version:
Function.prototype.bind = Function.prototype.bind || function (context) {
var me = this;
var args = Array.prototype.slice.call(arguments.1);
var F = function () {};
F.prototype = this.prototype;
var bound = function () {
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs);
return me.apply(this instanceof F ? this : context || this, finalArgs);
}
bound.prototype = new F();
return bound;
}
/ / modify
Function.prototype.myBind = function(obj) {
// Call bind must be a function
if(typeof this! = ="function") {
throw new Error('error')};var args = Array.prototype.slice.call(arguments.1);
var fn = this;
var fn_ = function () {};
var instanceObj = function () {
var params = Array.prototype.slice.call(arguments);
fn.apply(this.constructor === fn ? this : obj, args.concat(params));
console.log(this);
};
fn_.prototype = fn.prototype;
instanceObj.prototype = new fn_();
return instanceObj;
};
Copy the code
See the implementation like this :(discuss together, you can write an article to show me oh)
bind: function bind(that) {
var target = this;
if(! isCallable(target)) {throw new TypeError('Function.prototype.bind called on incompatible ' + target);
}
var args = array_slice.call(arguments.1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
array_concat.call(args, array_slice.call(arguments)));if ($Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
array_concat.call(args, array_slice.call(arguments))); }};var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
array_push.call(boundArgs, '$' + i);
}
bound = Function('binder'.'return function (' + boundArgs.join(', ') + '){ return binder.apply(this, arguments); } ')(binder);
if (target.prototype) {
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
}
Copy the code
extension
Documents on MDN:
The bind() method creates a new function that, when called, sets its this keyword to the supplied value and, when the new function is called, provides the sequence of arguments to be given before any supply
The apply() method calls a function with a specified this and arguments supplied as an array
Es6 mode, for example:
Function.protype.myCall = function(context) {
var context = context || window;
context.fun = this;
var args = [];
for(var i=1, len = arguments.length; i<len; i++) {
args.push(arguments[i]); } context.fun(... args)delete context.fun
}
Copy the code
Function.prototype.myCall = function(context,... args) {
context = context || window;
context.fun = this;
lettemp = context.fun(... args);delete context.fun;
return temp;
}
Copy the code
Note: Never use eval!
Js in the new ()
Can you explain what you do with the new operator in JS
Create an empty object
2. Link to the prototype
3. Bind this to the constructor
4. Make sure you return an object
Example:
var obj = new da();
var obj = {};
obj.__proto__ = da.prototype;
da.call(obj);
Copy the code
function A(){}
var a = new A();
a.__proto__ === A.prototype //true
/ / prototype chain
A.__proto__ === Function.prototype //true
Copy the code
Added: prototype and __proto__
Every function has a Prototype property, and every object instantiated by that function contains an implicit pointer (__proto__) to the function’s Prototype property
New operator
- Create an empty JavaScript object
{}
- Link this object to another object
- Use the newly created object as the context for this
- If the function does not return an object, this is returned
Example:
function da(name, age, year) {
this.name = name;
this.age = age;
this.year = year;
}
const da1 = new da('dada'.'12'.2333);
console.log(da1.name);
// expected output: "dada"
Copy the code
function create(){
// Create an empty object
let obj = new Object(a);// Get the constructor
let Constructor = [].shift.call(arguments);
// Link to the prototype
obj.__proto__ = Constructor.prototype;
/ / bind this
let result = Constructor.apply(obj,arguments);
// Return a new object
return typeof result === "object" ? result : obj;
// let obj = new Object();
}
Copy the code
Object. Create simulation implementation:
Object.create = function( o ) {
function f(){}
f.prototype = o;
return new f;
};
Copy the code
Thank you for bringing up the error
Regardless of the order
Gold digger net friend: know oneself ignorance
Little Aliens ღ
reference
If calm down to see the words will certainly have a harvest!
The CALL and apply methods are not used to emulate the BIND method of ES5
[suggestion 👍] 40 more this interview questions sour cool continue (1.2W words with hand arranged)
JavaScript deep simulation of call and apply
JavaScript in-depth simulation of bind implementation
Interviewer: Can you simulate the JS bind method
about
Author: Often mix trace in front river’s lake. Personal blog github blog, beg a star^_^~
Front end of wechat public account Dada
May be more interesting wechat public number, long press scan code attention. You can also add wechat xiaoda0423, indicate the source, pull you into [Dada front end communication group]. – Indicate source