// ES5 function User(name,age) { this.name = name; this.age = age; } // 靜態方法 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 } }) // 子類 function Manager(name,age,password){ User.call(this,name,age); this.password = password } // 繼承靜態方法 Manager.__proto__ = User // 繼承原型方法 Manager.prototype = User.prototype; //添加新方法 Manager.prototype.changePassword = function(pwd){ this.password = password } var manager = new Manager('leo',22,'123'); manager.changeName('zengliang'); console.log(User.name) //User console.log(manager.name) //zengjiang function test(){ console.log("1") } console.log(test.name) //test
ES6this
// function User(name,age) { // this.name = name; // this.age = age; // } class User { constructor(name,age){ this.name = name; this.age = age; } // // 靜態方法 // User.getClassName = function(){ // return 'User' // } static getClassName(){ return 'User' } // 方法的定義 // User.prototype.changeName = function(name){ // this.name = name // } // User.prototype.changeAge = function(Age){ // this.Age = Age // } changeName(name){ this.name = name } changeAge(age){ this.age = age } // 自定義屬性 // Object.defineProperty(User.prototype,'info',{ // get(){ // return 'name'+this.name+'age'+this.age // } // }) get info(){ return 'name'+this.name+'age'+this.age } } // 子類 // function Manager(name,age,password){ // User.call(this,name,age); // this.password = password // } class Manager extends User{ // 和call的區別,call先建立自身對象 constructor(name,age,password){ // super先建立父對象 必須 super(name,age); this.password = password } // //添加新方法 // Manager.prototype.changePassword = function(pwd){ // this.password = password // } changePassword(password){ this.password = password } get info(){ var info = super.info; console.log(info) } } // 下面的靜態方法跟原型方法已經繼承了,無須寫其餘的 // // 繼承靜態方法 // Manager.__proto__ = User // // 繼承原型方法 // Manager.prototype = User.prototype; console.log(typeof User,typeof Manager)//function function // var manager = new Manager('leo',22,'123'); // manager.changeName('zengliang'); // console.log(User.name) //User // console.log(manager.name) //zengjiang // function test(){ // console.log("1") // } // console.log(test.name) //test
不會提高spa
// // 當即執行 // let user = new class User{ // constructor(name){ // this.name = name // } // }('zengliang'); // console.log(user) // 會報錯,由於不會提高 // var user = new User() // class User{ // constructor(name){ // this.name = name // } // }