写这个话题单纯是给自己做笔记了,不然老忘记。
第一种方法:
|
1
2
3
4
5
6
7
8
9
10
|
function
fn1(x) {
this
.x = x;
}
function
fn2(x, y) {
this
.tmpObj = fn1;
this
.tmpObj(x);
delete
this
.tmpObj;
this
.y = y;
}
|
第二种方法:call()或apply()
|
1
2
3
4
5
6
7
8
|
function
fn1(x) {
this
.x = x;
}
function
fn2(x, y) {
fn1.call(
this
, x);
this
.y = y;
}
|
第三种方法:原型链继承
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
function
fn1(x) {
this
.x = x;
}
fn1.prototype.y =
function
() {
console.log(
"i am pomelo"
);
}
function
fn2() {}
fn2.prototype =
new
fn1();
fn2.prototype.constructor = fn2;
var
fn2Obj =
new
fn2();
fn2Obj.y();
|
实际用得最多的是第二种和第三种。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
function
fn1(x) {
this
.x = x;
}
fn1.prototype.z =
function
() {
console.log(
"i am pomelo"
);
}
function
fn2(x, y) {
fn1.apply(
this
, [x]);
this
.y = y;
}
fn2.prototype =
new
fn1();
fn2.prototype.constructor = fn2;
var
fn2Obj =
new
fn2(1024, 2048);
console.log(fn2Obj.x);
console.log(fn2Obj.y);
fn2Obj.z();
|
本文转自 iampomelo 51CTO博客,原文链接:http://blog.51cto.com/iampomelo/1677585,如需转载请自行联系原作者