1.extends
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString(){
return this.x + ' ' + this.y;
}
}
class ColorPoint extends Point {
constructor(x, y, color) {
//this.color = color; // ReferenceError
super(x, y);
this.color = color; // 正确
}
toString() {
return this.color + ' ' + super.toString(); // 调用父类的 toString()
}
}
let cp = new ColorPoint(25, 8, 'green');
console.log(cp instanceof ColorPoint )// true
console.log(cp instanceof Point) // true
console.log(cp.x)//25
console.log(cp.toString())//green 25 8
2.箭头函数
前言:es6箭头函数没出现之前,this的指向不是函数被创建时绑定,而是被怎么样的方式调用时绑定的。而箭头函数刚好相反,箭头函数的this指向是函数被创建时绑定的,它的指向就是当前词法作用域中的this,并且不会因为被怎么样的方式调用改变绑定。
ES6中箭头函数VS普通函数的this指向_慕课手记 https://www.imooc.com/article/288214
function foo() {
setTimeout(function(){
console.log('id:', this.id);
}, 100);
}
var id = 21;
foo.call({ id: 42 });//21
function foo1() {
setTimeout(()=>{
console.log('id1:', this.id1);
}, 100);
}
var id1 = 21;
foo1.call({ id1: 42 });//42
function Timer() {
this.s1 = 0;
this.s2 = 0;
// 箭头函数
setInterval(() => this.s1++, 1000);
// 普通函数
setInterval(function () {
this.s2++;
}, 1000);
}
var timer = new Timer();
s2=0;
setTimeout(() => console.log('s1: ', timer.s1), 3100);//3
setTimeout(() => console.log('s2: ', timer.s2), 3100);//0
setTimeout(() => console.log('s2: ', s2), 3100);//0
console.log(s2);//0
var x = 11;
var obj = {
x: 22,
say(){
console.log(this.x);
},
say1: ()=>{
console.log(this.x);
},
say2:function(){
var fn = () => console.log(this.x); // this指向obj对象
return fn();
},
}
obj.say(); // 22
obj.say1(); // 11
obj.say2(); // 22
const obj = {
num: 10,
hello: function () {
console.log(this); // obj
setTimeout(function () {
console.log(this); // window
});
},
hello1: function () {
console.log(this); // obj
setTimeout(() => {
console.log(this); // obj
});
}
}
obj.hello();
obj.hello1();