首页 > web前端 > js教程 > Objects in JavaScript

Objects in JavaScript

Susan Sarandon
发布: 2024-09-19 22:30:49
原创
1076 人浏览过

Objects in JavaScript

has key-value pairs, separated by colon. The key is also known as property
Similarity: index of arrays are replaced by keys in objects.
Object literal syntax is directly writing properties inside {}
Order during retrieval does not matter in case of objects whereas order matters in arrays.

Arrays: used for structured data
Objects: used for unstructured data

Property lookup methods in objects:

  1. using dot notation
  2. using brackets notation: key is defined as string in [] inside quotes, the key name can be an expression also. Ex. obj['firstName']; Ex. obj[2+3]; Putting an expression won't work with dot notation. We need to use the final property name, and not the computed property name.

Hence, when we have a computed property name its recommended to use brackets notation.

undefined will be returned if a property doesn't exist and we try to access it.

obj['insta-id'] = '@juju';

Refer operator precedence table on MDN for more info.

Object Methods

Fns are a type of value. Hence, we can create key-value pair in which the value is a fn. Means, we can add fns to objects.
Fn expression becomes methods inside objects i.e a fn attached to an object as a value for a key.
Fn declaration inside an object won't work.
method is also a property on the object which holds a fn value.
We can have values in the form of : array, string, boolean, fn etc.
obj.propName(); // will get the fn value and execute it using the ()

'this' : refers to the object on which its called

const person = {
  fName: 'Raja',
  lName: 'Rajeshwar',
  bYear: 1970,
  job: 'King',
  friends: ["Billu","Penchu","Ramesh"],

  calcAge: function(){
    // this will be the object which has called this method.
    // Its used to reference the object, and not hardcode it.
    console.log(this);
    // a new property is created on the person object named 'age'
    this.age = 2024 - this.bYear
    return this.age;
  }
}

person.calcAge(1970);
// age property will only exist if this fn was called atleast once else it won't exist.
person.age;
登录后复制

Arrays, Fns are all under the hood objects in JS. Hence, they have their own methods.

以上是Objects in JavaScript的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板