1. 構造器/原型模式
(1). 構造函數與原型模式的組合是ES5中定義自定義類型的常見方式。
其中,
- 構造函數模式定義對象的屬性
- 原型模式定義對象的方法
如:function Animal(name, age){
this.name = name; // 初始化屬性name
this.age = age;
};
Animal.prototype.eat = function (food) {
return 'Eat ' + food;
}; // 定義方法eat()
(2). ES6引入了類class關鍵詞,使構造函數/原型模式更便於應用。
如:class Animal {
constructor(name, age) {
this.name = name;
this.age = age;};
eat (food) {
return 'Eat ' + food;};
};
let cat = new Animal('cat', 5);
console.log(cat.eat('fish')); // 'Eat fish'
2. 原型的繼承 prototypal inheritance
(1). 在ES5中實現原型繼承的標準方法
- 使用Object.create(proto, [propertiesObject])方法
如:let cat = Object.create(animal,
{name: {value: 'cat'},
eat: {value: function(food){ return 'Eat ' + food; }}
});
3. this 關鍵詞
(1). this 引用的是當前正在調用的函數的對象。
如:let animal = {
name: 'cat',
age: 6,
greeting: function () { return `Hi, I'm a ` + this.name;}
};
console.log(animal.greeting()); // 'Hi, I'm a cat'
(2). 在全局範圍中,this引用的是全局對象,也就是瀏覽器的窗口對象。
如:console.log(this === window); // true
(3). 在非嚴格模式中 non-strict mode,this引用的是全局對象。
如:function hi () {
console.log(this === window);
};
hi(); // true
(4). 在嚴格模式中 strict mode,JavaScript將函數内部的this設爲undefined。
如:“use strict”;
function hi () {
console.log(this === undefined);
};
hi(); // true
(5). 使用bind()方法將this與指定對象綁定。
如:let cat = {
name: 'cat',
greet: function () { return `Hi, I'm a ` + this.name; }
};
let dog = {
name: 'dog'
};
let sayHi = cat.greet.bind(dog);
console.log(sayHi()); // Hi, I'm a dog
(6). this 在箭頭函數 Arrow functions 中的使用
- 箭頭函數不創建自己的執行環境,它是從定義箭頭函數的外層函數中繼承this。
如:let example = () => this;
console.log(example() === window);
// true 因爲example的外層函數即全局對象,所以this引用的是窗口對象。
(7). globalThis
- ES2020引入了globalThis,它可以在不同的環境中使用,而不需要使用不同的語法(如,window、frames、self或global)。