js繼承
阿新 • • 發佈:2020-11-27
Person物件類的匯出類Person.js程式碼如下
//建立物件
function Person(name,age){
//給屬性表賦值
this.name = name;
this.age = age;
}
//獲得物件的名字
Person.prototype.getName = function(){
return this.name;
}
//獲得物件的年紀
Person.prototype.getAge = function(){
return this.age;
}
//到對物件
module.exports = Person;
//繼承部分 //第一個匯出一個類 //匯出Person類 let personObj = require("./Person"); //建立普通的物件 let per = new personObj("小熊",22); console.log(per.getName()); console.log(per.getAge()); //end //繼承 function woman(name,age,sex){ this.name = name; this.age = age; this.sex = sex; } //直接賦值賦值看一下 // woman.prototype = personObj.prototype; 這種方式是錯誤的 for(var fuc in personObj.prototype){ woman.prototype[fuc] = personObj.prototype[fuc]; } console.log(woman.prototype) console.log("woman增加方法") woman.prototype.getSex = function(){ return this.sex; } console.log("woman增加方法後") console.log(woman.prototype) //建立物件 let m = new woman("小熊",34,"男"); console.log(m.getName()); console.log(m.getAge()); console.log(m.getSex());