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 —— 原型链

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43921423/article/details/113813425