JavaScript中的原型与原型链机制
原创什么是原型
JavaScript是一种基于原型的语言,每个对象都有一个原型(prototype)对象,对象从原型继承属性和方法。当试图访问一个对象的属性时,如果该对象本身没有这个属性,JavaScript会沿着原型链向上查找,直到找到该属性或到达原型链的末端(null)。
// 创建一个简单的对象const person = { name: '张三', age: 25, greet() { console.log(`你好,我是${this.name}`); }};// 使用Object.create基于person创建新对象const student = Object.create(person);student.major = '计算机科学';console.log(student.name); // "张三" - 从原型继承student.greet(); // "你好,我是张三" - 从原型继承console.log(student.major); // "计算机科学" - 自身属性构造函数与原型
在JavaScript中,函数可以有原型对象,当使用new关键字调用函数作为构造函数时,新创建的对象会继承构造函数的原型。
function Person(name, age) { this.name = name; this.age = age;}// 在原型上添加方法Person.prototype.greet = function() { console.log(`你好,我是${this.name},今年${this.age}岁`);};const person1 = new Person('李四', 30);person1.greet(); // "你好,我是李四,今年30岁"// 检查原型关系console.log(person1.__proto__ === Person.prototype); // trueconsole.log(Person.prototype.__proto__ === Object.prototype); // true原型链
JavaScript中的对象形成了一条原型链,当访问一个对象的属性时:
首先检查对象自身是否有该属性如果没有,检查对象的__proto__(即它的原型)继续沿着__proto__链向上查找,直到找到属性或到达nullfunction Student(name, age, major) { Person.call(this, name, age); this.major = major;}// 设置Student的原型为Person的实例Student.prototype = Object.create(Person.prototype);Student.prototype.constructor = Student;// 添加Student特有的方法Student.prototype.study = function() { console.log(`${this.name}正在学习${this.major}`);};const student1 = new Student('王五', 20, '物理学');student1.greet(); // "你好,我是王五,今年20岁" - 继承自Personstudent1.study(); // "王五正在学习物理学" - 自身方法// 原型链关系console.log(student1.__proto__ === Student.prototype); // trueconsole.log(Student.prototype.__proto__ === Person.prototype); // trueconsole.log(Person.prototype.__proto__ === Object.prototype); // true现代JavaScript中的类语法
ES6引入了class语法,但它仍然是基于原型的语法糖。
class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name}发出声音`); }}class Dog extends Animal { constructor(name, breed) { super(name); this.breed = breed; } speak() { console.log(`${this.name}(${this.breed})汪汪叫`); }}const myDog = new Dog('阿黄', '金毛');myDog.speak(); // "阿黄(金毛)汪汪叫"// 原型关系仍然存在console.log(myDog.__proto__ === Dog.prototype); // trueconsole.log(Dog.prototype.__proto__ === Animal.prototype); // true理解原型和原型链是掌握JavaScript对象模型的关键,它解释了JavaScript如何实现继承和属性查找机制。
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权本站发表,未经许可,不得转载。
开发学习网




