关于javascript:原型属性和方法-实例属性和方法-静态属性和方法

原型属性和办法:所有人独特应用一个
实例属性和办法:每个人都有一份
动态属性和办法:不能在类的实例上调用静态方法,而应该通过类自身调用。

实现继承的办法

  1. 原型链继承

让Man函数继承Person函数,须要让Man.prototype(Man的原型对象)的原型链(__proto__)指向Person的原型(Man.prototype),即Man.prototype.__proto__ = Person.prototype;

function Person(name){
 this.name = name; // 每个实例的名字不同,所以叫实例上的属性
}
Person.prototype.eat = function(){
    console.log(this, '我会吃');
}

function Man(name){
    this.name = name
}

Man.prototype.__proto__ = Person.prototype;
const man1 = new Man('张三');


console.log(man1.eat); // [Function]
  1. ES6中的setPrototypeOf办法实现继承
function Person(name){
 this.name = name; // 每个实例的名字不同,所以叫实例上的属性
}
Person.prototype.eat = function(){
    console.log(this, '我会吃');
}

function Man(name){
    this.name = name
}

// Man.prototype.__proto__ = Person.prototype;

Object.setPrototypeOf(Man.prototype, Person.prototype)
const man1 = new Man('张三');
console.log(man1.eat); //[Function]
  1. Object.create办法实现继承
function Person(name){
 this.name = name; // 每个实例的名字不同,所以叫实例上的属性
}
Person.prototype.eat = function(){
    console.log(this, '我会吃');
}

function Man(name){
    this.name = name
}

// Man.prototype.__proto__ = Person.prototype;

// Object.setPrototypeOf(Man.prototype, Person.prototype)

Man.prototype = Object.create(Person.prototype);

const man1 = new Man('张三');
console.log(man1.eat); //[Function]
// create原理
 function create(parentPrototype) {
   function Fn() {}
   Fn.prototype = parentPrototype;
   return new Fn();
 }
  1. extends语法

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理