Javascript 原型继承小例子

时间:2022-03-10 13:04:14


//1.实现一个Person类,公有成员name,私有成员age,有公有方法setAge
function Person() {
var age = "this is a private property age" //私有成员 age
this.name = "sophia"; //公有成员 name
this.setAge = function() { //公有方法setAge
console.log(age);
}
}


//2.实现一个Teacher类,继承Person类,公有成员name1,私有成员 score, 私有方法setScore 公有方法sayName
function Teacher() {
var score = "this is a private property score";
var setScore = function(){ //私有方法
console.log(score)
}
this.name1 = "sophia1";
this.sayName = function() { //公有方法setAge
console.log(name1);
}
}
Teacher.prototype = new Person();