class Person {
constructor(name){
this.name = name;
this.age = 18 ;
}
}
const zhangSan = new Text('张三'); // zhangSan.name => '张三' zhangSan.age => 18
class Person {
constructor(){
this.getName= function(){ console.log('张三') } ;
}
getAge() { console.log('18') }
}
const zhangSan = new Text();
zhangSan.getName(); //正常执行
zhangSan.getAge(); //正常执行
写在 constructor 函数 内、外的方法都可以执行,那么区别在哪里呢 ?
class Person {
constructor(){
this.getName= function(){ console.log('张三') } ;
}
getName() { console.log('李四') }
}
const zhangSan = new Text();
zhangSan.getName(); // 张三
在类里 constructor外 加方法 === Person.prototype 上加
class Test {
static hello() {
console.log('hello Class');
}
}
Test.hello();
在类里 static hello() === Test.hello = function(){ … }
| 类型 | 内容 |
|---|---|
| extends 继承 | 实例属性√ 原型属性√ 静态属性√ |
| 实例化 继承 | 实例属性√ 原型属性√ 静态属性 × |
class Text{
constructor(a){
this.a=a;
}
fun(){ /*...*/ }
}
let classA = new Text(1);
class Father{
fun(){ /*...*/ }
}
class Son extends Father{
constructor(age){
super();
this.age = age;
}
}
class Person {
constructor(x, y, color) {
this.height= '180cm';
this.weight= '60kg';
}
static hello() { console.log('hello Class'); }
}
class Zhangsan extends Person {
constructor(weight) {
super(x, y);
this.weight= weight;
}
}
Zhangsan.hello() //正常继承
class Test {
constructor() { /*...*/ }
get prop() {
return 123;
}
set prop(value) {
console.log('set: '+ value);
}
}
let inst = new MyClass();
inst.prop; // 123
inst.prop = 111; // 'set: 111'
拦截该属性的存取行为