JavaScript继承方式(2)
这篇开始写几个工具函数实现类的扩展。每个工具函数都是针对特定的写类方式(习惯)。这篇按照构造函数方式写类:属性(字段)和方法都挂在this上。以下分别提供了个类,分别作为父类和子类。
02
|
function
Person(nationality) {
|
03
|
????
this
.nationality = nationality;
|
04
|
????
this
.setNationality =
function
(n) {
this
.nationality=n;};
|
05
|
????
this
.getNationality =
function
() {
return
this
.nationality;};
|
10
|
????
this
.name = name;
|
11
|
????
this
.setName =
function
(n){
this
.name=n;};
|
12
|
????
this
.getName =
function
(){
return
this
.name;};
|
?
1,继承工具函数一
6
|
function
extend(subCls,superCls,param) {
|
7
|
????
superCls.call(subCls.prototype,param);
|
使用如下
1
|
extend(Man,Person,
'China'
);
|
2
|
var
m =
new
Man(
'jack'
);
|
3
|
console.log(m.nationality);
|
4
|
console.log(m.setNationality(
'Japan'
));
|
5
|
console.log(m.getNationality(
'Japan'
));
|
输出可以看到Man继承了Person的属性及所有方法。这种继承方式于java的很不一样哦,
10
|
public
class
Person
extends
Animal{
|
14
|
????
Person(
int
legs, String name) {
|
15
|
????????
super
(legs);
|
16
|
????????
this
.name = name;
|
19
|
????
String getName() {
|
20
|
????????
return
this
.name;
|
22
|
????
public
static
void
main(String[] args) {
|
24
|
????????
Person p =
new
Person(
2
,
"jack"
);???????
|
25
|
????????
System.out.println(p.legs);
|
Java中,子类Person在自身构造方法中调用父类构造方法super(legs),创建对象的时候直接将父类构造参数legs:2传进去,不
仅仅只传自己的name:jack。上面JavaScript继承是在extend时传父类构造参数(extend函数的第三个参数),而不是在new
Man时将父类构造参数传过去。好,模拟Java来实现下extend,这里巧妙的在子类上暂存了父类引用。
?
2,继承工具函数二
2
|
?
* @param {Function} subCls
|
3
|
?
* @param {Function} superCls
|
5
|
function extend(subCls,superCls) {?
|
6
|
????
subCls.supr = superCls;
|
还是以Person为父类,来实现子类Woman
1
|
function
Woman(nationality,name) {
|
2
|
????
Woman.supr.call(
this
,nationality);
|
3
|
????
this
.name = name;
|
4
|
????
this
.setName =
function
(n){
this
.name=n;};
|
5
|
????
this
.getName =
function
(){
return
this
.name;};
|
6
|
}<br>extend(Woman,Person);<br>
|
最后,创建对象的方式和java也类似,即new的时候同时将父类构造参数(nationality:Japan)传进去。
1
|
var
w =
new
Woman(
'Japan'
,
'lily'
);
|
2
|
console.log(w.nationality);
|
3
|
w.setNationality(
'U.S.A'
);
|
4
|
console.log(w.getNationality());
|