你真的懂原型继承(JavaScript)吗?

如果你还不了解原型和原型链,请看我对JavaScript原型的理解

请看一个关于原型继承的例子。

function Person(){
   this.name = 'father';
}
function Son(){
   console.log(name); // 这里打印为空
    console.log(Son.prototype.name); // 这里打印为father
}
Son.prototype =new Person();
new Son();

我一开始也对这个现象很奇怪, 奇怪在哪呢? 根据原型链,在执行console.log(name)的时候,在当前对象里找不到name, 然后应该是顺着原型链往上找,直到找到name,问题来了,name存在Son.prototype上,可是为什么打印为空呢?也不是打印undefined,或者出错,这真是太奇怪了。

再来看一个例子:

function Person(){
   this.name = 'father';
}
function Son(){
}
Son.prototype =new Person();
var obj = new Son();
console.log(obj.name); // name
看了这个例子应该明白了吧? 原型继承是对于Object类型的对象

总结一: 原型继承需要将子类实例化(创建Object类型对象)之后,才能访问到继承的属性。

PS: 未完待续


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript 中,原型继承可以通过以下几种方式来实现: 1. 构造函数继承:通过在子类构造函数中调用父类构造函数来实现属性继承。在子类构造函数中调用父类构造函数可以使用 call 或 apply 方法实现。 ```js function Parent(name) { this.name = name; } function Child(name, age) { Parent.call(this, name); this.age = age; } ``` 2. 原型继承:通过将子类的原型对象指向父类的实例来实现原型继承。 ```js function Parent() {} Parent.prototype.sayHello = function() { console.log('Hello'); } function Child() {} Child.prototype = new Parent(); Child.prototype.constructor = Child; ``` 3. 组合继承:通过将构造函数继承原型继承结合起来,既可以继承属性,也可以继承方法。 ```js function Parent(name) { this.name = name; } Parent.prototype.sayHello = function() { console.log('Hello'); } function Child(name, age) { Parent.call(this, name); this.age = age; } Child.prototype = new Parent(); Child.prototype.constructor = Child; ``` 4. 原型继承:通过 Object.create 方法创建一个新对象,并将该对象的原型指向一个已有的对象,从而实现继承。 ```js var parent = { name: 'parent', sayHello: function() { console.log('Hello'); } }; var child = Object.create(parent); child.age = 18; ``` 5. 寄生式继承:通过在原型继承的基础上,增强新对象,从而实现继承。 ```js function createChild(parent) { var child = Object.create(parent); child.sayName = function() { console.log(this.name); } return child; } var parent = { name: 'parent' }; var child = createChild(parent); child.sayName(); ``` 6. 寄生组合式继承:通过在组合继承的基础上,优化父类实例的创建,从而实现继承。 ```js function Parent(name) { this.name = name; } Parent.prototype.sayHello = function() { console.log('Hello'); } function Child(name, age) { Parent.call(this, name); this.age = age; } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值