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

3次阅读

共计 1254 个字符,预计需要花费 4 分钟才能阅读完成。

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

实现继承的办法

  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 语法
正文完
 0