JavaScript prototype object, object prototype - { }

JavaScript - Constructors

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

JavaScript - static methods

// 静态方法(只可用【构造函数】名字调用,不可用【实例对象】名字调用)
Player.turnover = function () {
    
    
    console.log('我会失误');
}
Player.turnover();
curry.turnover();	// 报错
  • curry.turnover();
    insert image description here

JavaScript - instantiating objects

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

JavaScript - Prototype Objects

(If the method is defined in the constructor, each time the object is instantiated, the method will be stored at a different address each time, and the function of [prototype object] is to store the same method of each object at the same storage address (In fact, only one method is generated), saving memory space)

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 - Object Prototypes

(Why the instantiated object can call the shot method on Player. Point to the Player.prototype prototype object)

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 - Constructor Properties

(The object prototype ( proto ) and the prototype object (prototype) both have an attribute constructor (constructor) attribute, which refers back to the constructor itself, and is mainly used to record the object [referenced to which constructor]. When we use the following method as When adding methods to Player.prototype (prototype object), you need to manually add the constructor attribute to let Player.prototype point back to the original constructor)

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 - the prototype chain

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43921423/article/details/113813425
Recommended