JS面向对象编程:b怎么继承a

JavaScript032

JS面向对象编程:b怎么继承a,第1张

function A(name){

this.name = name

this.sayHello = function(){alert(this.name+” say Hello!”)}

}

function B(name,id){

this.temp = A

this.temp(name) //相当于new A()

delete this.temp

this.id = id

this.checkId = function(ID){alert(this.id==ID)}

}

继承方法一、利用call或者apply方法改变this的指针,

function A(name,age){

this.age = age ? age : 25

this.name = name ? name : '小明'

this.say = function(){

alert(this.name + '今年' + this.age + '岁了!')

}

}

function B(name,age){

A.apply(this,arguments)

}

C = new B('小刚',18)

C.say()

继承方法二、

function A(name,age){

this.age = age ? age : 30

this.name = name ? name : '小明'

this.say = function(){

alert(this.name + '今年' + this.age + '岁了!')

}

}

function B(){}

B.prototype = new A()

var C = new B()C.say()

<script type = "text/javascript">

//父类

function Person(name, age) {

//属性

this.name = name

this.age = age

}

//方法

Person.prototype.showName = function() {

alert(this.name)

}

Person.prototype.showAge = function() {

alert(this.age)

}

//子类

function Coder(name, age, job) {

//继承父类的属性

//调用父类的构造方法

Person.call(this, name, age)

//增加自己的属性

this.job = job

}

//通过原型链继承父类的方法

Coder.prototype = Person.prototype

//增加自己的方法

Coder.prototype.showJob = function() {

alert(this.job)

}

//创建一个对象测试

var programer = new Coder('pro', '25', 'programer')

programer.showName()

programer.showAge()

programer.showJob()

</script>