es5:
//这种写法跟传统的面向对象语言(比如 C++ 和 Java)差异很大
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.say = function(){
return '我的名字叫'+this.name+',我今年'+this.age+'岁了!'
}
var xiaoming = new Person('小明',26)
xiaoming.say()
//三:静态方法
Person.walk = function(){
console.log("我会走路")
}
Person.walk() // 我会走路
xiaoming.walk() //TypeError
//四:原型继承
function Child(firstName, lastName, age) {
Parent.call(this, firstName, lastName)
this.age = age
}
Child.prototype = Object.create(Parent.prototype)
Child.constructor = Child
//五:get,set
function Number(param) {
//这里的_num和get/set方法num()不能重名
this._num = param
}
//get/set方法使用同一个命名,增加可读性
Number.prototype = {
get num() {
return this._num;
},
set num(newValue) {
this._num = newValue;
}
}
var test = new Number(8);
console.log(test.num);
test.num = 88;
console.log(test.num);
es6:
//这个就很接近于传统面向对象语言
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
say(){
return `我的名字叫${this.name},我今年${this.age}岁了!`
}
//三:静态方法
static walk(){
return '我会走路'
}
//五:get,set
get love() {
return 'getter';
}
set love(value) {
console.log('setter: '+value);
}
}
//静态方法可通过父类调用
//四:继承
class People extends Person{
static walk(){
return super.walk()+',我还会跑步'
}
}
//静态方法通常这样调用(直接用类名,不在实例中哦,切记)
console.log(Person.walk()) //我会走路
console.log(People.walk()) //我会走路,我还会跑步
var xiaohong = new Person('小红',12)
xiaohong.say()
//五:get,set
xiaohong.love = '小明'
xiaohong.love
//虽然引入了class关键字,但ES6中并没有真的引入类这个概念,通过class定义的仍然是函数
//class仅仅是通过更简单直观的语法去实现原型链继承。这种对语言功能没有影响、但是给程序员带来方便的新语法,被称为语法糖
//二:在类的参数传递中我们用constructor( )进行传参。传递参数后可以直接使用this.xxx进行调用
五,get,set
class Num {
constructor(num) {
this._num = num;
}
get num() {
return this._num;
}
set num(num) {
this._num = num;
}
}
var test = new Num(9);
console.log(test.num);
test.num = 99;
console.log(test.num);