Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js __proto__

作者:醉眼看苍生   发布日期:2026-01-10   浏览:82

// 示例代码:使用 __proto__ 属性

// 定义一个构造函数
function Animal(name) {
    this.name = name;
}

// 给 Animal 的原型添加一个方法
Animal.prototype.speak = function() {
    console.log(this.name + ' makes a noise.');
};

// 创建一个 Animal 实例
const animal = new Animal('Generic Animal');

// 定义另一个构造函数,继承自 Animal
function Dog(name, breed) {
    Animal.call(this, name); // 调用父类的构造函数
    this.breed = breed;
}

// 设置 Dog 的原型为一个新的对象,该对象的原型是 Animal.prototype
Dog.prototype = Object.create(Animal.prototype);

// 修正 Dog.prototype.constructor 指向 Dog
Dog.prototype.constructor = Dog;

// 给 Dog 添加自己的方法
Dog.prototype.bark = function() {
    console.log(this.name + ' barks.');
};

// 创建一个 Dog 实例
const dog = new Dog('Rex', 'German Shepherd');

// 使用 __proto__ 查看原型链
console.log(dog.__proto__); // Dog.prototype
console.log(dog.__proto__.__proto__); // Animal.prototype
console.log(dog.__proto__.__proto__.__proto__); // Object.prototype
console.log(dog.__proto__.__proto__.__proto__.__proto__); // null

// 调用方法
dog.speak(); // Rex makes a noise.
dog.bark(); // Rex barks.

// 解释说明:
// __proto__ 是一个对象的内部属性,指向其原型对象。
// 在上面的例子中,我们通过 __proto__ 查看了 Dog 实例的原型链:
// dog -> Dog.prototype -> Animal.prototype -> Object.prototype -> null

如果你需要更深入的解释或有其他问题,请告诉我!

上一篇:js 异步执行

下一篇:js dispatch

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站