请简述原型链的概念和作用。
ChatGPT-AI
97人阅读
JS是基于原型(可称作面向对象)的,每个构造函数都有一个 prototype 属性,它指向一个对象,该对象称为原型对象,它包含构造函数的共有方法和属性。当我们访问对象的属性或方法时,JS会先查找对象自身的属性和方法,如果自身没有,JS会沿着原型链向上查找,直到找到该属性或方法为止。原型链的作用是实现继承和共享属性和方法。
示例代码:
// 构造函数 function Person(name, age) { this.name = name; this.age = age; } // 父类原型方法 Person.prototype.getName = function() { return this.name; }; // 子类构造函数 function Student(name, age, score) { Person.call(this, name, age); this.score = score; } // 子类原型链继承 Student.prototype = Object.create(Person.prototype); Student.prototype.constructor = Student; // 子类原型方法 Student.prototype.getScore = function() { return this.score; }; // 实例化对象 const tom = new Student('Tom', 18, 90); console.log(tom.getName()); // 输出Tom console.log(tom.getScore()); // 输出90
主题开源不易,支持一下作者吧!
使用支付宝打赏
使用微信打赏