The opening

Isntanceof is used to determine the type and return a Boolean value. New is used to instantiate a class function. Let’s implement these two methods.

Implement instanceof

Example scenario

// Declare variables
const str = '123'
const num = 123

/ / print
console.log(str instanceof String) // true
console.log(num instanceof Number) // true
Copy the code

We can see that the instanceof body is divided into left and right sides. The left side is the type to be checked, and the right side is the target type.

implementation

/ / the main function
function newInstanceof(current, target) {
	// Get the left __proto__
    let left = current.__proto__
    
    // Get the prototype on the right
    let right = target.prototype
    
    // The while loop looks for __proto__ on the left
    while(left) {
    	if(left === right) {
        	return true
        }
        
        left = left.__proto__
    }
    
    return false
}

/ / test
const res1 = newInstanceof('123'.String)
console.log(res1) // true

const res2 = newInstanceof(123.Number)
console.log(res2) // true
Copy the code

__proto__ refers to the prototype of the constructor that constructed the object. Prototype refers to properties and methods that are shared by all instances, and is usually called a prototype object. All objects have a __proto__ attribute, while Prototype is only available for function objects.

Implement new

Example scenario

function Foo(value) {
	this.value = value
    
    return value
}

Foo.prototype.set = function() {
	console.log(this.value)
}

const res = new Foo('init')

res.set() // init
res.value // init
Copy the code

As you can see from the above code, the new object has all of the prototype properties and private properties of the instantiated object

function Foo(value) {
	this.value = value
    
    return {
    	obj: 'return object'}}const res = new Foo('init')
console.log(res) // {obj: 'return object'}

Copy the code

Two Foo functions that return a normal type and instantiate to get an inherited object; Return a reference type, instantiated to get that type, based on this feature let’s implement

implementation

function newInstanceof(fn,... args) {
	// create a new object and assign fn to get prototype
    const obj = Object.create(fn.prototype)
    
    // Change fn's this pointer to obj
    constres = fn.call(obj,... args)return res instanceof Object ? res : obj 
}

// Test returns a reference type
function Foo(value) {
	this.value = value
    
    return {
    	obj: value
    }
}

const res = newInstanceof(Foo, 'init')
res.obj // init

// The test returns a normal type
function Bar(value) {
	this.value = value
    
    return this.value
}
const resBar = newInstanceof(Bar, 'bar')
resBar.value // bar
Copy the code

conclusion

So far the operation mechanism of Instanceof and new has been implemented, please feel free to point out any questions in the comments.