[JavaScript]Prototype继承

JavaScript相对于其他的编程语言是比较简单的,只要吃透了Prototype和Closure(闭包),基本上就可以说精通JavaScript了。

JavaScript里如何实现向Java语言的OO的一下概念。下面列举了继承的三种写法:

// 这种写法只能复制base里的静态方法, 连base.prototype也不会复制
function extend(base, dest) {
	for (var i in base) {
		dest[i] = base[i];
	}
}

// 这种写法只能复制Prototype,静态函数和变量是不会被复制的
function extend1(base, dest) {
	for (var i in base.prototype) {
		dest.prototype[i] = base.prototype[i];
	}
}

// 这种方法是除了静态方法,其他的都会被复制
function extend2(base, dest) {
	dest.prototype = new base();
	dest.prototype.constructor = dest;
}

// 所有的都会被复制
function extend3(base, dest) {
	for (var i in base) {
		dest[i] = base[i];
	}
	dest.prototype = new base();
	dest.prototype.constructor = dest;
}

 测试实例如下(可在NodeJS运行查看结果):

function Base() {
	this.a = 1;
	this.b = function () {
		return 'b'
	};
}
Base.prototype.c = 1;
Base.prototype.d = function () {
	return 'd';
};
Base.e = 2;
Base.f = function () {
	return 'f';
}

function Derived() {
	this.g = 'g';
}
extend2(Base, Derived); // ===

Derived.prototype.h = function () {
	return 'h';
}
Derived.i = function () {
	return 'i';
}
function Derived1() {
	this.j = 'j';
}
extend2(Derived, Derived1); // ===
Derived1.prototype.k = function () {
	return 'k';
}

// test
console.log('================');
console.log(Base.prototype);
console.log(Derived.prototype);
console.log(Derived1.prototype);
console.log('================');

var o = new Derived1();
console.log('constuctor:' + o.constructor);
console.log("===Base===")
console.log("a:" + ('a' in o));
console.log("b:" + ('b' in o));
console.log("c:" + ('c' in o));
console.log("d:" + ('d' in o));
console.log('e:' + ('e' in Derived1));
console.log('f:' + ('f' in Derived1));
console.log("===Derived===")
console.log('g:' + ('g' in o));
console.log('h:' + ('h' in o));
console.log('i:' + ('i' in Derived1));

extend1还有另一种写法

function extend1(base, dest) {
	dest.prototype = base.prototype;
	dest.prototype.constructor = dest;
}

 有点奇怪把,通过for in语句并不能得到constructor属性。

原文地址:https://www.cnblogs.com/buhaiqing/p/3366359.html