JavaScript 之 原型对象、对象原型 —— { }

JavaScript —— 构造函数

// 构造函数
function Player(name, age) {
    this.name = name;
    this.age = age;
}

JavaScript —— 静态方法

// 静态方法(只可用【构造函数】名字调用,不可用【实例对象】名字调用)
Player.turnover = function () {
    console.log('我会失误');
}
Player.turnover();
curry.turnover();	// 报错
  • curry.turnover();
    在这里插入图片描述

JavaScript —— 实例化对象

let curry = new Player('库里', 21);
let young = new Player('杨', 21);

JavaScript —— 原型对象

(在构造函数中定义方法的话,每次当实例化对象的时候,每次都会在不同的地址上存储方法,而【原型对象】作用是把各个对象相同的方法都存放在同一个存储地址上(其实就只生成了一个方法),节省内存空间)

Player.prototype.shot = function () {
    console.log('我会射球');
}
curry.shot();
young.shot();
// 打印:curry.shot === young.shot: true
console.log(`curry.shot === young.shot: ${curry.shot === young.shot}`);

JavaScript —— 对象原型

(为什么实例化出来的对象能调用Player.prototype【原型对象】上的shot方法呢,是因为每个实例化出来的对象中都包含有一个__proto__【对象原型】,而这个对象原型__proto__指向Player.prototype原型对象)

console.log(curry);
// 打印:curry.__proto__ === Player.prototype: true
console.log(`curry.__proto__ === Player.prototype: ${curry.__proto__ === Player.prototype}`);
// 只要是对象就有__proto__原型,指向原型对象(prototype)
// Player.prototype.__proto__指向的是Object.prototype
// 而Object.prototype.__proto__指向的是 null
console.log(Player.prototype.__proto__ === Object.prototype);	// 打印:true
console.log(Object.prototype.__proto__);						// 打印:null
  • console.log(curry);

JavaScript —— 构造函数属性

(对象原型(proto) 和 原型对象(prototype)里面都有一个属性constructor(构造函数)属性,它指回构造函数本身,主要用于记录对象【引用于哪个构造函数】,当我们用下列方式为Player.prototype(原型对象)添加方法的时候,需要手动添加constructor属性让Player.prototype指回原来的构造函数)

Player.prototype = {
	constructor: Player,
	shot: function () { },
	turnover: function () { }
}
console.log(Player.prototype.constructor);
console.log(curry.__proto__.constructor);
  • console.log(Player.prototype.constructor);
  • console.log(curry.__proto__.constructor);
    console.log(Player.prototype.constructor);console.log(curry.__proto__.constructor);

JavaScript —— 原型链

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微风拂晚霞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值