//1.3
let user = {
name: 'xx'.
get name() {
return this.name;
},
set name(value) {
this.name = value //这句话报错了
}
};
user.name = "Peter"; //尝试赋值的时候报错Uncaught RangeError: Maximum call stack size exceeded
//解决方法
let user = {
_name:'xx',
get name() {
return this._name;
},
set name(value) {
this._name = value //设置一个中转变量
}
};
//1.4
class SetVar{
m=2;
set m(d){this.m=d}
}
let d=new SetVar();
d.m=99;//{m:99}
类方法之间不需要逗号分隔,加了会报错
类的内部所有定义的方法,都是不可枚举的(non-enumerable)。
class Point {
constructor(x, y) {
// ...
}
toString() {
// ...
}
}
Object.keys(Point.prototype)// []
类与模块为严格模式,不需要声明 use strict;
类必须使用new调用,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用new也可以执行。
function m(){console.log(new.target===m)}
m()//false
new m()// true 通过这个可以强制函数通过new来调用
类不存在变量提升(hoist),这一点与 ES5 完全不同。
new Foo(); // ReferenceError
class Foo {}
方法多层嵌套,this指向问题解决
1.箭头函数
2.重新赋值 如 let _t= this;
3.绑定this指向
class Logger {
constructor() {
this.printName = this.printName.bind(this);
}
// ...
}
基类默认构造方法
constructor() {}
派生类,默认构造函数
constructor(...args) {
super(...args);
}
//-------
class A {constructor(a){this.a=a;}};
class B extends A{}
new B(1)//{a:1}
派生类可以继承父类的属性与方法
类的实例化
调用 new 类名(参数a,b...),实际执行constructor构造方法,接收参数,实例化一个实例对象
类的所有实例共享一个原型对象 类名.prototype
继承与覆盖
class A {
x=1;
y(){}
z(){console.log('a')}
}
class B{
constructor(a){if(a){this.m=a;}}
m=2;
z(){console.log('b')}
}
let p= new B(9);//m值=9;
p.z();//'b' 覆盖了父类的z方法
let p1= new B();// m值=2
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);
ES6 的类,完全可以看作构造函数的另一种写法。
class Point {
// ...
}
typeof Point // "function" 类的数据类型就是函数
Point === Point.prototype.constructor // true 类本身就指向构造函数
类有prototype和__proto__ ,对象实例只有__proto__
function Foo(){}
let p= new Foo();
/*
p.__proto__===>Foo.prototype(其__proto__===>Object.prototype(其__proto__===>null))
Foo.prototype,Object.prototype,Function.prototype都是由构造函数创建的
自定义构造方法的__proto__=>Function.prototype(其__proto__==>Object.prototype)
见github 图
*/