原型和Class学习

75 阅读1分钟

原型和原型链

当通过 构造函数 或者 const obj={} 等方式 创建一个对象 时:


const newObject={    
    a:1
}
console.log( newObject)

function CreateObj(a){ 
   this.a=a;}
const obj=new CreateObj(1);

console.log(obj)

创建的  对象上 会有一个  [[prototype]] 属性 。[[prototype]] 指向就是该对象的【原型】,【原型】对象也会有自己的[[prototype]],这样的链条状的原型继承就被成为【原型链】。

**Object 实例的 __proto__ 访问器属性暴露了此对象的 [[Prototype]](一个对象或 null)。
**

[[prototype]]是只读的,要操作[[prototype]]需要访问newObj.__proto__属性

【obj.__proto__】  和 【构造函数的prototype】

设置对象的原型可以直接使用obj.__proto__,当对象是由构造函数创建的时候时,

我们可以设置Function.prototype继承另一个原型(当然也可以创建对象后,通过obj.__proto__设置)。

**如面的图片:**obj.__proto__ 继承 Object.prototype,Object.prototype继承null

即 newObject.__proto__==Object.prototype ,然后Object.prototype.__proto__===null

class和构造函数的对照

构造函数创建对象的[[prototype]]上的constructor等于构造函数的prototype的 constructor

相当于class里的constructor

function FnObject(fnValue) {        this.fnValue=fnValue;    
}
FnObject.prototype.test=function (){    
    console.log(this.fnValue)
}
FnObject.fnStaticValue=1;class ClassObject {       
    static staticValue=1;
    constructor(classValue) { 
        this.classValue=classValue;
    }    test(){
        console.log(this.classValue)    }
}
 // 构造函数的函数体 相当于 class的constructorconsole.log(new  ClassObject(1).__proto__.constructor===ClassObject.prototype.constructor)
console.log(new FnObject(1).__proto__.constructor===FnObject.prototype.constructor)
// Class声明的方法相当于构造函数的prototype上声明的方法
console.log(new ClassObject(1).__proto__.test===ClassObject.prototype.test)
console.log(new FnObject(1).__proto__.test===FnObject.prototype.test)// FnObject.fnStaticValue相当于ClassObject.staticValue

class的extends 相当于在构造函数prototype的__proto__添加值;