javascript 类继承机制

本文详细解释了JavaScript中类的继承机制,包括如何通过constructor和prototype实现类的继承,以及如何利用原型链访问和设置类属性。
Javascript类的继承是通过constructor和prototype来实现的

[size=small]1. 定义一个形如java的person类,然后实例化和调用它的属性[/size]

// Define a so called class
var person = function() {
this.name = "vulnerability";
this.age = 28;
}

// Instantiate the class
var p1 = new person();
alert(p1.name);

执行结果是:
vulnerability

[size=small]2. 定义一个person的子类man[/size]

var man = function() {
this.show = function() {
alert("The man is showing himself");
}
}

// Let the man extend the person
man.prototype = p1;

// Instantiate the man class
var m1 = new man();

// Invoke the show method
m1.show();

prototype是设置在class上而不是实例化过的对象中
执行结果是:
The man is showing himself

[size=small]3. 拿一个未设置的属性[/size]

alert(m1.name);

js解析器会从首先从当前对象去找这个属性,如果没有则顺着其原型对象链(prototype chain)去找这个属性值,如果翻遍了还没有,返回undefined。
执行结果是:
vulnerability

[size=small]4. 设置属性[/size]

// Set the property of the instance of subclass
m1.name = 'susceptibility';

// Verify whether the property has been set to the instance
alert(m1.name);

// Verify whether the property of the instance of prototype
// has been modified
alert(p1.name);

js在当前对象增加(更新)该属性,所以是在m1上设置。而原型对象的属性没有被改变
执行结果是:
susceptibility
vulnerability

[size=small]5. 设置原型对象的属性[/size]

// Set the property of the prototype of man
man.prototype.name = 'changed value';

// The property of the instance of subclass wouldn't be changed
alert(m1.name);

// The property of the prototype has been changed
alert(p1.name);

原型对象的属性被改变,但是子类对象没有。
执行结果是:
susceptibility
changed value
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值