function Parent() { this.name = 'red'; this.eat = function () { console.log('走这里了吗') } } Parent.prototype.start = function () { console.log(this.name) } function Children() {}
Children的原型对象=Parent的原型对象
缺点:
实例对象p指向Parent;
实例对象p不能调用构造函数Parent的方法和属性,只能调用Parent的原型对象的方法和属性
//仅继承了Parent原型对象上的方法和属性 Children.prototype = Parent.prototype let p = new Children(); console.log(p.name)//undefined console.log(p.eat)//undefined console.log(p.start) //ƒ () { // console.log(this.name); //} console.log(p.constructor) //ƒ Parent() { // this.name = 'red'; // this.eat = function () { // console.log('走这里了吗'); // }; }
Children.prototype = new Parent()
缺点:
实例对象p指向Parent
Children.prototype = new Parent()//继承了Parent的原型对象prototype的方法和属性以及constructor let p = new Children(); console.log(p)//Children {} console.log(p.name)//red console.log(p.start) //ƒ () { // console.log(this.name); // } console.log(p.eat) // ƒ () { // console.log('走这里了吗'); // } console.log(p.constructor) // ƒ Parent() { // this.name = 'red'; // this.eat = function () { // console.log('走这里了吗'); // }; // }
Children.prototype = new Parent()
Children.prototype.constructor = Children;
Children.prototype = new Parent()//继承了Parent的原型对象prototype的方法和属性以及constructor Children.prototype.constructor = Children; let p = new Children(); console.log(p.constructor); // ƒ Children() {}
缺点
- 如果父构造函数中含有引用类型的属性,当某个实例改变了该引用类型的属性,则所有实例共享该实例(基本数据类型不会)
- 创建Children实例无法传参
function Parent() { this.name = 'red'; this.arr = [1, 2, 3]; this.eat = function () { console.log('走这里了吗') } } Parent.prototype.start = function () { console.log(this.name) } function Children() { } Children.prototype = new Parent(); Children.prototype.constructor = Children let p1 = new Children() let p2 = new Children() console.log(p1.arr) p1.name = 'blue'; p1.arr.pop(); console.log(p1.name)//blue console.log(p2.name)//red console.log(p1.arr)//[2,3] console.log(p2.arr)//[2,3]