JS构造函数,原型__proto__,原型对象prototype(详细+代码)

本文详细介绍了如何通过构造函数创建对象,包括实例化过程、原型对象的作用,以及如何更改属性和拓展原型。重点讲解了构造函数与原型的关系以及相关操作的实际效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建对象的多种方式
https://blog.youkuaiyun.com/tinyint_813/article/details/115396219?spm=1001.2014.3001.5501

创建构造函数发生的事情

1. 基础知识

注意:构造函数名称首字母最好大写,在创建实例的时候用new关键字创建。
通过构造函数Student可以创建实例对象stu,stu的__proto__指向Student的原型对象,而Student的原型对象prototype的构造对象指向它本身。

function Student(name, age){
    this.name = name;
    this.age = age;
}
let stu = new Student("ccc","23");
console.log(stu);
console.log(stu.__proto__);
console.log(Student.prototype);
console.log(stu.__proto__ === Student.prototype);
console.log(stu.__proto__.constructor);
console.log(stu.__proto__.constructor === Student);
console.log(Student.prototype.constructor === Student);

得到的结果为

Student { name: 'ccc', age: '23' }
{}
{}
true
[Function: Student]
true
true

解释:任何构造函数都有原型对象prototype,默认为空对象。所以在不给它设值的时候,它默认为{}

2. 更改值的问题
①更改属性值(不为对象)

3.拓展

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值