Skip to content

Instantly share code, notes, and snippets.

@FrankFan
Last active August 29, 2015 14:17
Show Gist options
  • Save FrankFan/7c0eb06ca2b3585bf497 to your computer and use it in GitHub Desktop.
Save FrankFan/7c0eb06ca2b3585bf497 to your computer and use it in GitHub Desktop.
Javascript中继承的几种写法

一、 基于class的继承, 用 funcion 实现

function Person(){
	this.name = 'person';
}

function Student(age, gender) {
	Person.apply(this, arguments);
	this.age = age;
	this.gender = gender;
}

// test code
var s = new Student(23, '男');
console.log(s.name + ' | ' + s.age + ' | ' + s.gender);

二、 基于原型的继承 用 prototype 实现

function Person(){
	this.name = 'person';
}

function Student(age, gender) {
	this.age = age;
	this.gender = gender;
}

Student.prototype = new Person();
Student.prototype.constructor = Student;

// test code
var s = new Student(23, '男');
console.log(s.name + ' | ' + s.age + ' | ' + s.gender);

三、混合继承

function Person(name) {
    this.name = name;
}

Person.prototype.getName = function() {
    return this.name;
}

function Author(name, books) {
    this.base = new Person(name);
    // 
    for(var key in this.base) {
        if(!this[key]) {
            this[key] = this.base[key];
        }
    }

    this.book = books;
}

// test code
var au1 = new Author('Tom', 'Javascript');
var au2 = new Author('Jerry', 'HTML5');
console.log('au1.name = ' + au1.getName() + ' , au1.book = ' + au1.book);
console.log('au2.name = ' + au2.getName() + ' , au2.book = ' + au2.book);

四、 深拷贝

function extend(p, c) {
	var c = c || {};

	for(var i in p) {
		if(typeof p[i] === 'object') {
			// 当前元素是对象, 继续处理
			c[i] = (p[i].constructor === Array) ? [] : {};
			// c[i] = (object.prototype.toString.call(p[i])) ? [] : {};

			// 递归调用
			extend(p[i], c[i]);
		} else {
			// 是简单值,直接赋值给child类
			c[i] = p[i];
		}
	}

	return c;
}

// test code
var Chinese = {
  nation: '中国'
};
Chinese.birthPlaces = ['北京','上海','香港'];
var Doctor = {
  career: '医生'
};
var Doctor = deepClone(Chinese, Doctor);
Doctor.birthPlaces.push('厦门');
console.log(Doctor.birthPlaces); //北京, 上海, 香港, 厦门
console.log(Chinese.birthPlaces); //北京, 上海, 香港
var parent = { arr: [1,2,3,4,5], hello: 'haha', world: 'hehe', myobj: {name: 'chrome', age: 22}};
var child = { a: '1', b: '2'};
var res = deepClone(parent, child);
console.log(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment