原型和继承

78 阅读1分钟

每一个实例对象(包含各种数据类型的实例对象)都有一个__proto__属性,该属性指向该实例对象的构造函数的原型。

  1. 构造函数都拥有原型prototype。
  2. 创建实例对象时构造函数把原型赋予该实例对象。
  3. Function构造函数创建一个新的Function对象,所以任何一个具体函数继承Function.prototype。包含各种数据类型的构造函数都继承Function.prptotype
各种数据类型实例化代码
//function
const sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 6));
//简写形式
function sum(a,b){
    return a+b;
}


// string
const str = new String('test');
//简写形式
const str = 'test';


//boolean
const flag = new Boolean(true)
//简写形式
const flag = true;

//number
const count = new Number(2);
//简写形式
const count = 2;


图片.png

可以根据 代码 验证上述理论

function User(name){

    this.name = name;

    this.show = ()=>{

        console.log(this.name);

    }

}

User.prototype.info = ()=>{

    console.log('get info');

}

const lisi = new User('李四');

// console.dir(User);

console.dir(lisi);

console.log(lisi.__proto__ === User.prototype);

console.log(User.__proto__ === Function.prototype);

console.log(Function.prototype.__proto__ === Object.prototype);

console.log(Object.prototype.__proto__);


const str = new String('test');

console.log(str.__proto__ === String.prototype);

console.log(String.__proto__ === Function.prototype);

console.log(String.prototype.__proto__ === Function.prototype.__proto__);

console.log(String.prototype.__proto__ === Object.prototype);

console.log(Function.prototype.__proto__ === Object.prototype);