這 6 點知識讓我對 JavaScript 的對象有了更進一步的了解
1. 對象方法 & this
方法只是保存函數(shù)值的屬性。
簡單對象方法
- let rabbit = {};
- rabbit.speak = function(line) {
- console.log("小兔子說: "+ line );
- };
- rabbit.speak("我還活著。")
輸出:
- T小兔子說: 我還活著。
對象方法 & this
當一個函數(shù)作為方法被調(diào)用時,對象會將函數(shù)作為屬性并立即調(diào)用,就像在object.method()中一樣,其主體中的特殊變量this將指向被調(diào)用的對象。
- function speak(line) {
- console.log(this.type + "小兔子說:" + line)
- };
- let whiteRabbit = {type: "白色", speak: speak}
- whiteRabbit.speak("噢,我真可愛!")
輸出:
- 白色小兔子說:噢,我真可愛!
apply & call
- function speak(line) {
- console.log(`${this.type}的小兔子說:${line}` );
- };
- let whiteRabbit = {type: "白色", speak: speak};
- speak.apply(whiteRabbit, ["你這個小壞蛋!"]);
- speak.call({type: "黑色"}, "嘿嘿,我不壞,你不愛!");
- 白色的小兔子說:你這個小壞蛋!
- 黑色的小兔子說:嘿嘿,我不壞,你不愛!
2.Prototype(原型)
- 幾乎所有的對象都有一個prototype
- prototype是另一個用作屬性的備用源的對象
- 當一個對象訪問自身沒有屬性時,它會從它的prototype搜索該屬性,如果沒有找到就繼續(xù)從它的prototype的prototype查找,依此類推,直到 null 為止。
空對象的原型
原型鏈最終的指向是Object的prototype, 而Object中的__proto__是null
- let empty = {};
- console.log(empty.toString);
- console.log(empty.toString());
輸出:
- [Function: toString]
- [object Object]
其他對象(數(shù)組、函數(shù)等等)的默認屬性
- 許多對象沒有直接將Object.prototype作為自己的原型,但有自己的默認屬性
- 從Function.prototype派生的函數(shù)和從Array.prototype派生的數(shù)組
- console.log(Object.getPrototypeOf(isNaN) ==
- Function.prototype);
- console.log(Object.getPrototypeOf([]) ==
- Array.prototype);
輸出:
- true
- true
- Object.create 創(chuàng)建具有特定原型的對象
- protoRabbit充當所有兔子共享的屬性的容器
單個兔子對象(如殺手兔子)包含僅適用于自身的屬性(在本例中為type),并從其原型派生共享屬性
- let protoRabbit = {
- speak: function (line) {
- console.log(`${this.type}兔子說:${line}` );
- }
- }
- let killerRabbit = Object.create(protoRabbit)
- killerRabbit.type = '殺手'
- killerRabbit.speak('準備受死吧!')
輸出:
- 殺手兔子說:準備受死吧!
3.構(gòu)造函數(shù)
— 構(gòu)造函數(shù)原型
- 創(chuàng)建從某個共享原型派生的對象的更方便的方法是使用構(gòu)造函數(shù)
- 在 JavaScript 中,調(diào)用前面帶有new關(guān)鍵字的函數(shù)會將其視為構(gòu)造函數(shù)
- 構(gòu)造函數(shù)將其this變量綁定到一個新對象,除非它顯式返回另一個對象值,否則此新對象將從調(diào)用中返回
- 用new創(chuàng)建的對象被稱為是其構(gòu)造函數(shù)的實例
- 約定將構(gòu)造函數(shù)的名稱大寫,以便于與其他函數(shù)區(qū)分開
- function Rabbit(type) {
- this.type = type;
- }
- let killerRabbit = new Rabbit("killer");
- let blackRabbit = new Rabbit("black");
- console.log(blackRabbit.type);
輸出:
- black
— 默認情況下,構(gòu)造函數(shù)具有Object.prototype
- 構(gòu)造函數(shù)(實際上是所有函數(shù))會自動獲取一個名為prototype的屬性,默認情況下,該屬性包含一個從Object.prototype派生的普通空對象
- 使用此構(gòu)造函數(shù)創(chuàng)建的每個實例都將此對象作為其原型
- function Rabbit(type) {
- this.type = type;
- }
- let blackRabbit = new Rabbit("黑色");
- Rabbit.prototype.speak = function(line) {
- console.log(`${this.type}的兔子說:${line}` );
- };
- blackRabbit.speak("Boom...一波王炸!");
輸出:
- 黑色的兔子說:Boom...一波王炸!
4. 重寫派生屬性
— 相同的原型名稱
- 如果原型中有同名的屬性,則不會更改此屬性
- 該屬性被添加到對象本身
- function Rabbit(type) {
- this.type = type;
- }
- let blackRabbit = new Rabbit("black");
- let killerRabbit = new Rabbit("killer");
- Rabbit.prototype.teeth = "small";
- console.log(killerRabbit.teeth);
- // small
- killerRabbit.teeth = "long, sharp, and bloody";
- console.log(killerRabbit.teeth);
- // long, sharp, and bloody
- console.log(blackRabbit.teeth);
- // small
- console.log(Rabbit.prototype.teeth);
- // small
下面 console.log(blackRabbit.teeth)的結(jié)果是small,因為blackRabbit對象不具有teeth屬性,它繼承自Rabbit對象自己的teeth屬性,值為 small。
5. 原型的干擾
— 可枚舉與不可枚舉
- let map = {}
- function storePhi(event, phi) {
- map[event] = phi
- }
- storePhi('pizza', 0.069)
- storePhi('touched tree', -0.081)
- Object.prototype.nonsense = 'hi'
- for(let name in map) {
- console.log(name)
- }
- console.log('nonsense' in map)
- console.log('toString' in map)
輸出結(jié)果:
- pizza
- touched tree
- nonsense
- true
- true
toString沒有出現(xiàn)在for/in循環(huán)中,但是in運算符中返回true,這是因為 JS 區(qū)分可枚舉屬性和不可枚舉屬性。
我們通過簡單分配創(chuàng)建的所有屬性都是可枚舉的,Object.prototype中的標準屬性都是不可改變的,這就是為什么它們不出現(xiàn)在這樣的for/in循環(huán)中的原因。
- let map = {};
- function storePhi(event, phi) {
- map[event] = phi;
- }
- storePhi("pizza", 0.069);
- storePhi("touched tree", -0.081);
- Object.defineProperty(Object.prototype, "hiddenNonsense",
- {enumerable: false, value: "hi"})
- for (var name in map) {
- console.log(name)
- }
- console.log(map.hiddenNonsense)
輸出:
- pizza
- touched tree
- hi
通過使用Object.defineproperty函數(shù)可以定義自己的不可枚舉屬性,該函數(shù)允許我們控制要創(chuàng)建的屬性的類型,在該示例中,hiddenNonsense在 map 中,但在 for...in 中不會顯示。
— hasOwnProperty vs in 操作符
- const map = {}
- console.log("toString" in map)
- console.log(map.hasOwnProperty("toString"))
輸出:
- true
- false
hasOwnProperty方法告訴我們對象本身是否具有該屬性,而無需查看其原型,這通常是比in運算符提供給我們的信息更有用的信息。
因此,如果你對基礎對象原型感到困惑時,建議你可以這樣寫for/in循環(huán):
- for (var name in map) {
- if (map.hasOwnProperty(name)) {
- // ... this is an own property
- }
- }
6.無原型對象
Object.create函數(shù)使我們能夠創(chuàng)建具有特定原型的對象。我們還可以傳遞null作為原型,用來創(chuàng)建不帶原型的新對象。
因此,我們不再需要hasOwnProperty,因為對象擁有的所有屬性都是它自己的屬性。現(xiàn)在,無論人們對Object.prototype做了什么,我們都可以安全地使用for/in循環(huán)
- var map = Object.create(null);
- map["pizza"] = 0.069;
- console.log("toString" in map);
- // false
- console.log("pizza" in map);
- // true
作者:Valentino Gagliardi 譯者:前端小智 來源:valentinog
原文:https://medium.com/javascript-in-plain-english/six-things-you-should-know-about-objects-in-javascript-ccd11a9e1998
本文轉(zhuǎn)載自微信公眾號「 大遷世界」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系****公眾號。