一、 基于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 ) ;