原型属性和方法:所有人共同使用一个
实例属性和方法:每个人都有一份
静态属性和方法:不能在类的实例上调用静态方法,而应该通过类本身调用。
实现继承的方法
- 原型链继承
让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]
- 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]
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();
}
extends语法
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。