javascript之过渡es6

js 过渡es6 时的 变量和继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// javascript中的var作用域;
// var的作用域只分为 全局和函数内,
// 1. 不加var声明的变量都是全局,应该尽量避免不要在函数内使用 a = 10; 会造成变量的全局污染。
// 不规范写法
var b=2;
function foo1() {
b=4;
console.log(b); //4
}
foo1();
console.log(b); //4
// 规范写法
var b=2;
function foo1() {
var b=4;
console.log(b); //4
}
foo1();
console.log(b); //2

// 在全局外 不用var声明的变量,也会自动变为全局变量
t=11;
console.log(t); //11
console.log("t" in window); //true


// 2.加上var关键字,也不一定在当前作用域生效
// 因为javascript中没有块级作用域
function foo() {
for(var i=0;i<10;i++){
console.log(i); //0,1,2,3,4,5,6,7,8,9
}
// 这里仍可以访问i
console.log(i); //10
}
foo();

/* 在es6 中
可以使用let来定义块级作用域变量
以及const关键字定义常量
以及函数新写法 sayHi() {}
以及箭头表达式 () => {}
以及模板字符串 `hi ${name}, ni hao`
以及解构表达式
等等sugar

以及下面介绍的class extends 常用的oop 中的关键字。
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// javascript原生实现继承。使用prototype
function Bear(type) {
this.type = type;
}
// third call
Bear.prototype.growl = function() {
console.log('the ' + this.type + ' bear says grrr');
};

function Grizzly() {
// call super constructor. 类似es6 中sugar的 constructor 中的 super('grizzly')
Bear.call(this, 'grizzly');
}
// 使用现有对象创建一个新对象,可以继续在prototype上添加Grizzly的私有属性
// 使用Object.create()来实现类式继承,类似es6中的 class Grizzly extends Bear{}
Grizzly.prototype = Object.create(Bear.prototype);

console.log(Bear.prototype.constructor); // [Function: Bear]
console.log(Grizzly.prototype.constructor); // [Function: Bear]
Grizzly.prototype.name = 'hehe' // name is a property set on ‘Grizzly.prototype’, but not on Bear.prototype

// second call
// Grizzly.prototype.growl = function() {
// console.log('on the grizzly prototype...');
// };

var grizzly = new Grizzly();

// first call
// grizzly.growl = function() {
// console.log('override...')
// };

Grizzly.growl = function() {
console.log('Grizzly method'); // 相当于类方法, 需要通过类名调用
}
Grizzly.growl() // Grizzly method
grizzly.growl() // the grizzly bear says grrr

console.log(grizzly instanceof Bear); // true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 下面我们用 es6 实现上面原生javascipt的继承。
class Bear {
constructor(type) {
this.type = type;
}
growl() {
console.log(`the ${this.type} bear says grrr`);
}
}

class Grizzly extends Bear {
constructor(type, name) {
super(type);
this.name = name;
}
static growl() {
console.log('Grizzly method');
}
}

let grizzly = new Grizzly('grizzly', 'dottie');
Grizzly.growl(); // Grizzly method
grizzly.growl(); // the grizzly bear says grrr