ES6 class
js中 原有方法
function Phone(brand, price) {
this.brand = brand;
this.price = price;
}
// 添加方法
Phone.prototype.call = function() {
console.log('我可以打电话');
}
// 实例化对象
let huawei = new Phone('华为', 999);
huawei.call();
console.log(huawei);
class
// class
class Phone1 {
// 构造方法 名字不能变
constructor(brand, price) {
this.brand = brand;
this.price = price;
};
// 方法 必须使用该语法
// 不能使用 ES5 的对象完整形式 call:function(){}
call() {
console.log('i can take phone');
}
}
let onePlus = new Phone1('1+', '999');
onePlus.call();
console.log(onePlus);
get set
// get set
class Phone {
// price;
get price() {
console.log('价格属性被读取了');
return 'ilove'
}
set price(newVal) {
console.log('价格属性被修改了');
}
}
let s = new Phone();
s.price = 'free';
console.log(s.price);
s.price = '789'
console.log(s.price);
输出 价格属性被读取了 价格属性被修改了 ilove
引入 price后 // 输出 free 789
类的静态成员
function Phone() {
}
Phone.name = '手机';
Phone.change = function() {
console.log('change');
}
Phone.prototype.size = '5.5inch';
let nokia = new Phone;
console.log(nokia.size); // 输出 5.5inch
class Phone1 {
static name = '手机';
static change() {
console.log('change111');
}
}
let ph = new Phone1();
Phone1.change(); // change111
console.log(ph.name); //undefined
console.log(Phone1.name); // 手机
类继承
// 手机
function Phone(brand, price) {
this.brand = brand;
this.price = price;
}
// 添加方法
Phone.prototype.call = function() {
console.log('我可以打电话');
}
// 智能手机
function smartPhone(brand, price, color, size) {
Phone.call(this, brand, price);
this.color = color;
this.size = size;
}
// 设置子级构造函数的原型
smartPhone.prototype = new Phone;
smartPhone.prototype.constructor = smartPhone; // 矫正代码 无影响 可以没有
// 声明子类的方法
smartPhone.prototype.photo = function() {
console.log('take photos');
};
smartPhone.prototype.game = function() {
console.log('play games');
};
let chuizi = new smartPhone('锤子', 4444, '黑色', '5.5inch')
console.log(chuizi); // smartphone
chuizi.call(); //我可以打电话
class Phone {
// 构造方法
constructor(brand, price) {
this.brand = brand;
this.price = price;
};
// 父类成员属性
call() {
console.log('i can take phone');
}
}
class smartPhone extends Phone {
//构造方法
constructor(brand, price, color, sieze) {
super(brand, price); //父类方法
this.color = color;
this.sieze = sieze;
}
photo() {
console.log('take photos');
}
game() {
console.log('play games');
};
call() {
console.log('视频通话');
}
}
let xiaomi = new smartPhone('小米', 888, '黑色', '4.7inch')
console.log(xiaomi); // smartPhone
xiaomi.call(); //视频通话
xiaomi.game(); //play games