Call, apply, bind, the new method, instanceOf, Object. Create, Object. Assign, realize the attributes of the Object the get and set methods

Call, apply, bind method implementation

Call method implementation

Calls a function with a specified this value and one or more arguments.

Key points:

  • This may be passed null;
  • Pass in an unfixed number of arguments;
  • A function may have a return value;
Function.prototype.mycall=function(obj){
    obj.fn=this;
    obj.fn();
    delete obj.fn;
}
console.log('mycall-------------')
fn.mycall(obj)

Function.prototype.mycall2=function(obj){
    // Check whether it is a function. Only functions have call methods
    if(typeof this! = ='function') {throw new TypeError('not function')}// When the call first argument is undefined or null, this points to window by default
    obj=obj||window;
    obj.fn=this;
    let args=[...arguments].slice(1)
    letres=obj.fn(... args)delete obj.fn;
    return res
}
console.log('mycall2-------------')
fn.mycall2(obj,222.111)
Copy the code
Apply method implementation

Apply is the same as call, except that call passes in an unlimited number of arguments, whereas apply passes in an array.

Key points:

  • This may be passed null;
  • Pass an array;
  • A function may have a return value;
Function.prototype.myapply=function(context){
    if(typeof this! = ='function') {throw new TypeError('err')
    }
    context=context||window
    context.fn=this
    let args=[...arguments].slice(1)
    let res;
    if(args.length>0){ res=context.fn(... args[0])}else{
        res=context.fn()
    }
    delete context.fn
    return res
}
Copy the code
Bind method implementation

The bind method creates a new function. When bind() is called, this of the new function is specified as the first argument to bind(), and the remaining arguments are used as arguments to the new function.

Key points:

  • Bind () can pass multiple arguments in addition to this;
  • New functions created by Bing may pass in multiple arguments;
  • New functions may be called as constructors;
  • A function may have a return value;
// Unlike call and apply, bind returns a function
Function.prototype.mybind=function(context){
    if(typeof this! = ='function') {throw new TypeError('err')}let _this=this
    let args=[...arguments].slice(1)
    // Instanceof checks if the prototype property of an instance object exists on the prototype chain.
    // this instanceof func === true, returns fBound as new constructor, this=fBound(){},
    // Otherwise this=window, if so, use the newly created this instead of hard-bound this
    return function F(){
        if(this instanceof F){
            return new_this(... args,... arguments) }else{
            return_this.apply(context,args.concat(... arguments)) } } }Copy the code

Implement new methods

The new operator works by creating a new object and linking the object to its stereotype 3. Bind this to the newly created object. 4. Return the new object

function createNew(){
    let obj={}// Create an object
    // So take an array object [], call shift, and pass arguments in as the first argument
    // Call this in object arguments to the Array type and then call the method on Array
    // equivalent to arguments.shift()
    //[].shift = array.prototype.shift
    // Take the object passed into the argument (the first argument is a function object)
    let constructor= [].shift.call(arguments);
    //obj.__proto__ is the same as object. prototype, which refers to the Object type prototype
    obj.__proto__=constructor.prototype; // Link the incoming object to the prototype of object type (obj)
    let result=constructor.apply(obj,arguments); // Bind obj's this to the incoming object and return the new object
    return typeof result==='object'? result:obj// If the function returns no value, the new object is returned, otherwise the function's return value is returned
}
function People(name,age) {
    this.name = name
    this.age = age
}
let peo = createNew2(People,'Bob'.22)
console.log(peo.name)
console.log(peo.age)
Copy the code

Implement instanceOf

Core idea: Determine if the prototype property of the right-hand constructor is present in the prototype chain of the left instance

function instanceOf(left,right) {
    let lefttype=left.__proto__;
    let righttype=right.prototype;
    while(true) {if(righttype===null) {return false;
        }
        if(lefttype===righttype){
            return true
        }
        lefttype=lefttype.__proto_
    }
}
let arr=[]
console.log(instanceOf(arr,Array))
Copy the code

To realize the Object. The create

The object.create () method creates a new Object, using an existing Object to provide the __proto__ of the newly created Object.

Object.create2 = function(proto, propertyObject = undefined) {
    if (typeofproto ! = ='object' && typeofproto ! = ='function') {
        throw new TypeError('Object prototype may only be an Object or null.')
    if (propertyObject == null) {
        new TypeError('Cannot convert undefined or null to object')}function F() {}
    F.prototype = proto
    const obj = new F()
    if(propertyObject ! =undefined) {
        Object.defineProperties(obj, propertyObject)
    }
    if (proto === null) {
        // Create an Object with no prototype Object, object.create (null)
        obj.__proto__ = null
    }
    return obj
}
Copy the code

To realize the Object. The assign

Object.assign2 = function(target, ... source) {
    if (target == null) {
        throw new TypeError('Cannot convert undefined or null to object')}let ret = Object(target) 
    source.forEach(function(obj) {
        if(obj ! =null) {
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    ret[key] = obj[key]
                }
            }
        }
    })
    return ret
}

Copy the code

Get and set methods to achieve object attributes

function Person(){ } 
Person.prototype.name="admin";
Person.prototype.getName=function(){
  return this.name;
};
Person.prototype.setName=function(val){
  this.name=val;
};
var per=new Person();
console.log(per.name)
Copy the code

Or (chainable call)

function Person(){ this.value=1; this.set=function(value){ this.value = value; return this; } this.get=function(){ return this.value; }}; var person = new Person(); console.log(person.set(100).get()) // 100Copy the code