1.ES5創(chuàng)建類
function User(name, age) {
this.name = name;
this.age = age;
}
// 靜態(tài)方法
User.getClassName = function () {
return 'User';
}
User.prototype.changeName = function (name) {
this.name = name;
}
User.prototype.changeAge = function (age) {
this.age = age;
}
Object.defineProperty(User.prototype, 'info', {
get() {
return 'name:' + this.name + ' | age:' + this.age;
}
});
/* var user = new User('lucky',30);
console.log(user.info); */
// 定義子類
function Manager(name,age,password) {
User.call(this,name,age);
this.password =password;
}
// 繼承靜態(tài)方法
Manager.__proto__ = User;
// 繼承prototype方法
Manager.prototype = User.prototype;
// 添加新方法
Manager.prototype.changePassword = function(password){
this.password = password;
}
var m = new Manager('xxxx',30,'123');
console.log(m.name);
m.changeName('yyyy')
console.log(m.name);
console.log(m.info);
1.ES6創(chuàng)建類
'use strict'
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
// 靜態(tài)方法
static getClassName() {
return 'User';
}
changeName(name) {
this.name = name;
}
// 定義屬性info
get info() {
return 'name:' + this.name + ' | age:' + this.age;
}
}
// 定義子類
class Manager extends User {
constructor(name, age, password) {
super(name, age);
this.password = password;
}
changePassword(password) {
this.password = password;
}
// 覆蓋父類info
get info() {
let info = super.info;
console.log(info);
return 'new info ------';
}
}
// let m = new Manager('baby',6,'123456');
// console.log(m.info);
// 對(duì)象沒(méi)有提升
//let em = new Employee('eeee',11);//出錯(cuò)
class Employee extends User {
// 默認(rèn)自動(dòng)加入constructor
// constructor(...args){
// super(...args);
// }
}
// let e = new Employee('zhangsan',20);
// console.log(e.info);
// 立即執(zhí)行類"實(shí)例化"
// let customer = new class Customer {
// constructor(name) {
// this.name = name;
// }
// }('lisi');
// console.log(customer);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。