前端面试常考 | js原型与原型链



一. 什么是原型?

在js中所有的引用类型都有一个__proto__(隐式原型)属性,属性值是一个普通的对象。
而在js中的引用类型包括:Object,Array,Date,Function
而所有函数都有一个prototype(原型)属性,属性值是一个普通的对象,也被称为原型对象
所有引用类型的__proto__属性指向它构造函数的prototype:

var a = [1,2,3];
a.__proto__ === Array.prototype; // true

那么原型有什么作用呢?

  1. 可以存放一些属性和方法:
Array.prototype.hello=function(){
    
    
	console.log("hello")
}
arr = [1, 2, 3]
arr.hello() // hello
  1. 在javaScript中实现继承:
    function Father(){
    
    
            this.firstName="李";
        }
        var father=new Father();
        Father.prototype.lastName="名";
        function Son(){
    
    
            this.firstName="张";
            this.sex="男";
        }
        // 子类原型继承父类的实例
        Son.prototype=father;
        var son=new Son();
        console.log(son.firstName,son.lastName,son.sex)

二. 什么是原型链?

当访问一个对象的某个属性时,会先在这个对象本身属性上查找,如果没有找到,则会去它__proto__隐式原型上查找,即它的构造函数的prototype,如果还没有找到就会再在构造函数的prototype的__proto__中查找,这样一层一层向上查找就会形成一个链式结构,我们称为原型链
注意: 如果最顶层还找不到的话就会返回null
列如我们有如下代码:

		Object.prototype.age = 18
        function Person(name) {
    
    
            this.name = name;
        }

        var preson = new Person('nt');
        console.log(preson.name); // nt
        console.log(preson.age); //18

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Siebert_Angers/article/details/128533884