JAVASCRIPT继承之一--对象冒充

原理:

构造函数使用this关键字给所有属性和方法赋值.因为构造函数只是一个函数,所以可使ClassA的构造方法称为ClassB的方法,然后调用它.

ClassB就会收到ClassA的构造方法中定义的属性和方法.


实战:

function Parent(username){
	this.username = username ;
this.sayHello = function(){
alert( this.username ) ;
}
}


function Child(username , password){
this.method = Parent ;
this.method( username ) ;
delete this.method ;
this.password = password ;
this.sayWorld = function(){
alert( this.password ) ;
}
}


var parent1 = new Parent( "jack" ) ;
var child1= new Child( "kyle" , "ABC" ) ;
parent1.sayHello() ;
child1.sayHello() ;
child1.sayWorld() ;


解释:

在Child中this.method(name)等价于以下代码:

	  this.username=username;
            this.sayHello=function(){
                alert( this.username ) ;
            }
Child代码就如下:

function Child(username , password){
this.method = Parent ;
this.username = username ;
this.sayHello = function(){
alert( this.username ) ;
}
delete this.method ;
this.password = password ;
this.sayWorld = function(){
alert( this.password ) ;
}
}

delete this.method 后

代码就变成这样:

function Child(username , password){
	this.username = username ;
	this.sayHello = function(){
		alert( this.username ) ;
	}
	this.password = password ;
	this.sayWorld = function(){
		alert( this.password ) ;
	}
}
从而实现了对象的冒充.


你可能感兴趣的:(JavaScript,function,delete)