XSS原型与原型链

概念说明

prototype和__proto__均为函数中的一种属性,区别在于prototype是构造函数的属性,用于定义实例共享的属性和方法,__proto__是实例的属性,指向创建它的构造函数的prototype

javascript 复制代码
function Animal(type) {
  this.type = type;
}

// 为构造函数的prototype添加方法
Animal.prototype.speak = function() {
  console.log(`I'm a ${this.type}`);
};

// 创建实例
const dog = new Animal('dog');
const cat = new Animal('cat');

// 验证实例的__proto__指向构造函数的prototype
console.log(dog.__proto__ === Animal.prototype);       // true
console.log(cat.__proto__ === Animal.prototype);       // true

// 验证构造函数的prototype.constructor指向自身
console.log(Animal.prototype.constructor === Animal);  // true

// 实例继承的方法来自prototype
console.log(dog.speak === Animal.prototype.speak);     // true
console.log(cat.speak === Animal.prototype.speak);     // true

原型链的层级结构

javascript 复制代码
const bird = new Animal('bird');

// 验证原型链的层级
console.log(bird.__proto__ === Animal.prototype);              // true
console.log(Animal.prototype.__proto__ === Object.prototype);   // true
console.log(Object.prototype.__proto__ === null);               // true(原型链终点)

// 通过原型链访问Object的方法
console.log(bird.toString === Object.prototype.toString);       // true
console.log(bird.hasOwnProperty === Object.prototype.hasOwnProperty); // true

改原型对实例的影响

javascript 复制代码
function Fruit(name) {
  this.name = name;
}

const apple = new Fruit('apple');
const banana = new Fruit('banana');

// 修改原型前
console.log(apple.color); // undefined

// 向原型添加属性
Fruit.prototype.color = 'unknown';

// 验证所有实例继承新属性
console.log(apple.color); 
console.log(banana.color); 
console.log(apple.color === Fruit.prototype.color); // true
相关推荐
张拭心3 分钟前
Android 17 新特性:MessageQueue 无锁实现
android·前端
Asize6 分钟前
数组数据结构底层:从灵活到陷阱
前端·javascript·算法
十九画生7 分钟前
Ajax 入门:用 XHR 理解前后端异步请求
前端·javascript·后端
yingyima7 分钟前
Python re 模块速查:从实战对比中掌握正则表达式
前端
放下华子我只抽RuiKe51 小时前
FastAPI 全栈后端(三):数据库与 ORM
前端·数据库·react.js·oracle·性能优化·前端框架·fastapi
梵得儿SHI2 小时前
Vue 项目实战与性能优化全攻略:从代码、渲染到首屏,一站式解决卡顿慢加载
前端·vue.js·性能优化·vite·前端面试·前端优化·首屏优化
ShyanZh2 小时前
【skill】HTML PPT Skill:用 Claude Code 一句话生成专业演示文稿
前端·ai·html·powerpoint·skill
AI视觉网奇2 小时前
three教学 3d资产拼接源代码
前端·css·css3
程序猿阿伟2 小时前
《Chrome标签组搭建多任务高效浏览指南》
前端·chrome
2601_958352903 小时前
双麦 DSP 音频模块实战:一文梳理 A-68 在全行业场景的声学解决方案与落地要点
前端·嵌入式硬件·音视频·语音识别·降噪消回音·音频处理模块