原型相关

145 阅读2分钟

构造函数

一个普通函数用new运算符来调用就是构造函数。

function Person (name) {
    this.name = name
}

let person = new Person ('Tom')
console.log(person) // {name: 'Tom'}

Function.prototype

每个函数都有一个prototype属性,在函数声明的时候js会给他自动添加这个属性,prototype指的是原型对象,会先初始化为一个空对象。

constructor

原型对象会有一个constructor属性,constructor默认指向的是声明的构造函数。

__proto__

创建出来的实例/对象会有一个__proto__属性,__proto__指向的是原型对象。

原型链

原型链就是根据实例的__proto__属性一层一层的往上链接,因为__proto__也是一个对象,所以他也会有他的__proto__, 当Object.prototype原型链就终止了


instanceof原理

instanceof的原理就是获取左边对象的__proto__属性是不是和右边构造函数的prototype是不是指向的是同一个引用,如果不是,会继续沿着左边原型链上的__proto__判断与右边prototype是不是同一个引用,如果有,就返回true,如果到原型链末端(__proto__ === Object.prototype)都不是,就返回false

网上找的实现代码:链接:juejin.cn/post/684490…

function new_instance_of(leftVaule, rightVaule) { 
    let rightProto = rightVaule.prototype; // 取右表达式的 prototype 值
    leftVaule = leftVaule.__proto__; // 取左表达式的__proto__值
    while (true) {
    	if (leftVaule === null) {
            return false;	
        }
        if (leftVaule === rightProto) {
            return true;	
        } 
        leftVaule = leftVaule.__proto__ 
    }
}

判断对象是否是某个构造函数直接实例方式

用构造函数来判断

function Foo () {}
let f = new Foo()
// f 是 Foo 的实例
console.log(f instanceof Foo)
// f 同时也是 Object 的实例
console.log(f instanceof Object)
// f 是 Foo 直接构建出来的实例
console.log(f.__proto__constructor === Foo)


顺便看看typeof

typeof

JS数据类型:number, string, boolean, undefined, null, symbol, object

原始类型:number, string, boolean, undefined, null, symbol

Object包括:Array, Function, Date, Error

typeof判断有:number, string, boolean, undefined, symbol, object, function

typeof 判断原理

www.zhihu.com/question/66…

typeof 是根据计算机存储的二进制判断

js 在底层存储变量的时候,会在变量的机器码的低位1-3位存储其类型信息

000:对象

010:浮点数

100:字符串

110:布尔

1:整数

null 是全 0

undefined 是 −2^30

typeof 的 Bug: typeof null === 'object'true


准确判断类型方法:

Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call("123");// "[object String]"
Object.prototype.toString.call(123);// "[object Number]"
Object.prototype.toString.call(true);// "[object Boolean]"

Function fn(){
  console.log(“test”);
}
Object.prototype.toString.call(fn); // "[object Function]"

var date = new Date();
Object.prototype.toString.call(date); // "[object Date]"

var arr = [1,2,3];
Object.prototype.toString.call(arr); // "[object Array]"

var reg = /[hbc]at/gi;
Object.prototype.toString.call(reg); // "[object RegExp]"

function Person(name, age) {
    this.name = name;
    this.age = age;
}
var person = new Person("Rose", 18);
Object.prototype.toString.call(arr); // "[object Object]"