These 6 points of knowledge gave me a better understanding of JavaScript objects

Author: Valentino Gagliardi
Translator: Front Ash
Source: valentinog

Like it and look again , WeChat search [Daqian World] focuses on this person who has no background in a big factory, but has a positive attitude towards upwards. This article has been included on GitHub https://github.com/qq449245884/xiaozhi , the article has been classified, and a lot of my documents and tutorial materials have been organized.

1. Object method & this

The method just saves the properties of the function value.

Simple object method

let rabbit = {};
rabbit.speak = function(line) {
    console.log("小兔子说: "+ line );
};
rabbit.speak("我还活着。")

Output:

T小兔子说: 我还活着。

Object method & this

When a function is called as a method, the object will use the function as an attribute and call it immediately, just like in object.method(), the special variable in its body thiswill point to the called object.


function speak(line) {
  console.log(this.type + "小兔子说:" + line)
};
let whiteRabbit = {type: "白色", speak: speak}

whiteRabbit.speak("噢,我真可爱!")

Output:

白色小兔子说:噢,我真可爱!

apply & call

  • applyAnd callcan be usedobject.method()

  • applycallBoth and methods have a first parameter that can be used to simulate method calls

  • In fact, the first parameter is used to specify this


function speak(line) {
  console.log(`${this.type}的小兔子说:${line}` );
};
let whiteRabbit = {type: "白色", speak: speak};

speak.apply(whiteRabbit, ["你这个小坏蛋!"]);
speak.call({type: "黑色"}, "嘿嘿,我不坏,你不爱!");
白色的小兔子说:你这个小坏蛋!
黑色的小兔子说:嘿嘿,我不坏,你不爱!

2.Prototype (prototype)

  • Almost all objects have aprototype

  • prototypeIs another object used as an alternate source of attributes

  • When an object is no access to their own property, it will from its prototypesearch of the property, if it does not find it from continuing prototypethe prototypesearch, and so on until nullso far.

The prototype of the empty object

The final point of the prototype chain is Object prototype, and the object in Object __proto__isnull

let empty = {};
console.log(empty.toString);
console.log(empty.toString());

Output:

[Function: toString]
[object Object]

Default properties of other objects (arrays, functions, etc.)

  • Many objects are not directly used Object.prototypeas their own prototypes, but have their own default properties
  • From the Function.prototypederived function and 从Array.prototypethe array derived
console.log(Object.getPrototypeOf(isNaN) ==
            Function.prototype);
console.log(Object.getPrototypeOf([]) ==
Array.prototype);

Output:

true
true

Object.create creates an object with a specific prototype

  • protoRabbitActs as a container for attributes shared by all rabbits

  • A single bunny object (such as a killer bunny) contains properties that only apply to itself (in this case type), and derives shared properties from its prototype



let protoRabbit = {
  speak: function (line) {
    console.log(`${this.type}兔子说:${line}` );
  }
}

let killerRabbit = Object.create(protoRabbit)
killerRabbit.type = '杀手'
killerRabbit.speak('准备受死吧!')

Output:

杀手兔子说:准备受死吧!

3. Constructor

— Constructor prototype

  • A more convenient way to create objects derived from some shared prototype is to use the constructor

  • In JavaScript, calling newa function with a keyword in front will treat it as a constructor

  • The constructor thisbinds its variables to a new object, unless it explicitly returns another object value, this new object will be returned from the call

  • With the newcreated object instance is said to be its constructor

  • It is agreed to capitalize the name of the constructor to distinguish it from other functions


function Rabbit(type) {
    this.type = type;
}

let killerRabbit = new Rabbit("killer");
let blackRabbit = new Rabbit("black");
console.log(blackRabbit.type);

Output:

black

— By default, the constructor has Object.prototype

  • The constructor (actually all functions) will automatically get a prototypeproperty named , by default, the property contains an Object.prototypeordinary empty object derived from

  • Every instance created using this constructor has this object as its prototype


function Rabbit(type) {
  this.type = type;
}

let blackRabbit = new Rabbit("黑色");
Rabbit.prototype.speak = function(line) {
  console.log(`${this.type}的兔子说:${line}` );
};
blackRabbit.speak("Boom...一波王炸!");

Output:

黑色的兔子说:Boom...一波王炸!

4. Override derived properties

— The same prototype name

  • If there is a property with the same name in the prototype, this property will not be changed
  • The attribute is added to the object itself

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

The following console.log(blackRabbit.teeth)result is that small, because the blackRabbitobject does not have a teethproperty, it inherited from Rabbitthe object's own teethproperty, value small.

5. Prototype interference

-Enumerable and non-enumerable

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)

Output result:

pizza
touched tree
nonsense
true
true

toStringIt does not appear in the for/inloop, but inreturns in the operator true. This is because JS distinguishes between enumerable properties and non-enumerable properties .

All the properties we create by simple assignment are enumerable, Object.prototypeand the standard properties in are immutable, which is why they do not appear in such a for/inloop.


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)

Output:

pizza
touched tree
hi

By using the Object.definepropertyfunction can not define your own enumerated attribute, the function allows us to control the type of property you want to create, in this example, hiddenNonsensein the map, but for...innot displayed.

-HasOwnProperty vs in operator

const map = {}
console.log("toString" in map)
console.log(map.hasOwnProperty("toString"))

Output:

true
false

hasOwnPropertyThe method tells us whether the object itself has the property without looking at its prototype, which is usually inmore useful information than the information provided to us by the operator.

Therefore, if you are confused about the base object prototype, it is recommended that you write a for/inloop like this :

for (var name in map) {
    if (map.hasOwnProperty(name)) {
        // ... this is an own property
    }
}

6. No prototype object

Object.createFunctions allow us to create objects with specific prototypes. We can also pass nullas a prototype to create a new object without a prototype.

Therefore, we no longer need it hasOwnProperty, because all the properties of an object are its own properties. Now, no matter what people Object.prototypedo right, we can safely use for/inloops


var map = Object.create(null);
map["pizza"] = 0.069;
console.log("toString" in map);
// false
console.log("pizza" in map);
// true

The talents' [Three Lian] is the biggest motivation for Xiaozhi to keep sharing. If there are any errors or suggestions in this blog, we welcome the talents to leave a message. Finally, thank you for watching.


The possible bugs after code deployment cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

Original: https://medium.com/javascript-in-plain-english/six-things-you-should-know-about-objects-in-javascript-ccd11a9e1998

The article is continuously updated every week, you can search on WeChat **[Daqian World] Read it for the first time, reply [welfare]** There are many front-end videos waiting for you, this article GitHub https://github.com/qq449245884/xiaozhi has Included, welcome to Star.

Guess you like

Origin blog.csdn.net/qq449245884/article/details/108526521