xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js Object.setPrototypeOf & Object.create All In One

js Object.setPrototypeOf & Object.create All In One

Object.setPrototypeOf 👎

function Animal (name, sound) {
  this.name = name;
  this.sound = sound;
}
Animal.prototype.shout = function () {
  console.log('name =', this.name, 'sound =', this.sound);
}

function Plants (name) {
  this.name = name;
  this.sound = null;
}
// 重载:方法名称相同,参数不同(参数个数不同或参数类型不同)
// 复写/覆盖/重写:方法名称相同,参数相同(内部实现逻辑不同,外部完全没变化)
Plants.prototype.shout = function (arg = '❓') {
  console.log('name =', this.name, 'sound =', this.sound);
  console.log('plants shout  =', arg);
}
Plants.prototype.getAlias = function () {
  console.log('alias =', this.name + ' tree 🌴');
}

// demo
const dog = new Animal('puppy','barking')
// 狗叫 barking

Object.setPrototypeOf(Animal.prototype, Plants.prototype);
console.log('Animal.prototype =', Animal.prototype);

const cat = new Animal('kitten', 'miaow')
// 猫叫 miaow

dog.shout('🐶');

cat.shout('😸');
cat.getAlias();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf

Object.create 👍

function Animal (name, sound) {
  this.name = name;
  this.sound = sound;
}
Animal.prototype.shout = function () {
  console.log('name =', this.name, 'sound =', this.sound);
}

function Plants (name) {
  this.name = name;
  this.sound = null;
}
// 重载:方法名称相同,参数不同(参数个数不同或参数类型不同)
// 复写/覆盖/重写:方法名称相同,参数相同(内部实现逻辑不同,外部完全没变化)
Plants.prototype.shout = function (arg = '❓') {
  console.log('name =', this.name, 'sound =', this.sound);
  console.log('plants shout  =', arg);
}
Plants.prototype.getAlias = function () {
  console.log('alias =', this.name + ' tree 🌴');
}

// demo
const dog = new Animal('puppy','barking')
// 狗叫 barking

Animal.prototype = Object.create(Plants.prototype)
console.log('Animal.prototype =', Animal.prototype);

const cat = new Animal('kitten', 'miaow')
// 猫叫 miaow

dog.shout('🐶');

cat.shout('😸');
cat.getAlias();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

refs

https://www.cnblogs.com/xgqfrms/p/15998513.html#5027756

https://www.youtube.com/watch?v=PFmuCDHHpwk

https://juejin.cn/post/6844903527941144589



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-03-13 16:22  xgqfrms  阅读(35)  评论(0编辑  收藏  举报