Objects

is JavaScript’s fundamental datatype

 

is a composite value which aggregates multiple values

(primitive values or other objects)

allows to store values and retrieve them by names

 

is an unordered collection of properties

each of which has a name and a value

 

string to value mapping is also known as

hash, hashtable, dictionary or associative array

Object

BUT

an object is more than just a simple string-to-value map

 

a JavaScript object also

inherits the properties of another object

known as its prototype

 

the methods of an object are typically inherited properties

and

this prototypal inheritance is a key feature of JavaScript

Objects are dynamic

so

properties can usually be added and deleted

but

they can be used to simulate the static objects

and “structs” of statically typed languages

 

they can also be used (by ignoring the value part of the string-to-value mapping) to represent sets of strings

 

any value that is not

a string, number, true, false, null or undefined is an object

 

and even strings, numbers and booleans

behave like immutable objects

 

recall that objects are mutable

and are manipulated by reference rather than by value

 

 

 

 

 

the fundamental operations:

create objects

and

set, query, delete, test, and enumerate properties

exemplu

if the variable x refers to an object, and the code var y = x; 
is executed, the variable y holds a reference to the same object,
not a copy of that object.
Any modifications made to the object through the variable y are 
also visible through the variable x

 

so an object is a collection of properties,

where each property has

 

a name

usually a string, including the empty string

but there can never be 2 properties with the same name

 

and

 

a value

either a primitive value or an object, never undefined

in addition, each property has

associated values that are called property attributes

 

the writable attribute

specifies whether the value of the property can be set

 

the enumerable attribute

specifies whether the property name is returned by a for/in loop

 

the configurable attribute

specifies whether the property can be deleted and
whether its attributes can be altered

 

starting with ECMA Script5, properties attributes can be configured

in addition to its properties,

every object has three associated object attributes


an object’s prototype is a reference to another object from which properties are inherited

 

an object’s class is a string that categorizes the type of an object

 

an object’s extensible flag specifies (in ECMAScript 5) whether new properties may be added to the object

 

categories of objects

 

native object

an object or class of objects defined by the ECMAScript specification (like arrays, functions, dates, and regular expressions)


host object

an object defined by the host environment (such as a web browser)
within which the JavaScript interpreter is embedded

(like HTMLElement objects that represent the structure of a web page in client-side JavaScript)
host objects may also be native objects, as when the host environment defines
methods that are normal JavaScript Function objects


user-defined object

any object created by the execution of JavaScript code

types of properties

 


own property

a property defined directly on an object

 


inherited property

a property defined by an object’s prototype object

Creating Objects

Creating Objects

with object literals

 

with the new keyword

 

with the Object.create() function

Object literals

Object literal =  a comma-separated list of colon-separated

name: value pairs, enclosed within curly braces

 

a property name is a JavaScript identifier or a string literal

(the empty string is allowed, 

no object may have two properties with the same name)

 

a property value is any JavaScript expression

 

in general property names that are reserved words must be quoted

an object literal is an expression that creates and initializes

a new and distinct object each time it is evaluated

=>

the value of each property is evaluated

each time the literal is evaluated

 

this means that a single object literal can create many

new objects if it appears within the body of a loop in a function that is called repeatedly, and that the property values of these objects may differ from each other

Object literals

new operator

the new operator creates and initializes a new object

the new keyword must be followed by a function invocation

 

a function used in this way is called a constructor and serves
to initialize a newly created object

 

core JavaScript includes built-in constructors for native types

Object(), Array(), Date(), RegExp()

 

in addition to these built-in constructors, it is common to define

own constructor functions to initialize newly created objects

a "constructor" in JavaScript is "just" a function that happens to be called with the new operator

Prototypes

every JavaScript object has a second JavaScript object associated with it (to which it has an internal link) which is known as its prototype

 

the first object inherits properties from the prototype

 

all objects created by object literals have

the same prototype object - Object.prototype

 

objects created using the new keyword and a constructor invocation use the value of the prototype property of the constructor function as their prototype

Prototype chain

each prototype object has a prototype of its own, so the links continue until an object is reached with null as its prototype

 

this linked series of prototype objects

is known as a prototype chain

 

null

by definition has no prototype

and

acts as the final link in the prototype chain

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain

 

Object.prototype is one of the rare objects

that has no prototype: it does not inherit any properties

 

other prototype objects are normal objects

that do have a prototype


all of the built-in constructors

(and most user-defined constructors)

have a prototype that inherits from Object.prototype

Prototype chain

Objects created with syntax constructs

var o = {a: 1};

// The newly created object o has Object.prototype as its [[Prototype]]
// o has no own property named 'hasOwnProperty'
// hasOwnProperty is an own property of Object.prototype. So o inherits hasOwnProperty from Object.prototype
// Object.prototype has null as its prototype.
// o ---> Object.prototype ---> null

var a = ["yo", "whadup", "?"];

// Arrays inherit from Array.prototype (which has methods like indexOf, forEach, etc.)
// The prototype chain looks like:
// a ---> Array.prototype ---> Object.prototype ---> null

function f(){
  return 2;
}

// Functions inherit from Function.prototype (which has methods like call, bind, etc.)
// f ---> Function.prototype ---> Object.prototype ---> null

Objects created with a constructor

function Graph() {
  this.vertices = [];
  this.edges = [];
}

Graph.prototype = {
  addVertex: function(v){
    this.vertices.push(v);
  }
};

var g = new Graph();
// g is an object with own properties 'vertices' and 'edges'.
// g.[[Prototype]] is the value of Graph.prototype when new Graph() is executed.

Object.create()

 a method that creates a new object,

using its first argument as the prototype of that object

 

the method also takes an optional second argument

that describes the properties of the new object

 

Object.create() is a static function, not a method invoked on individual objects (???)

Text

// create new object that has no prototype, inherits no properties or methods
var o1 = Object.create(null);

// create an ordinary empty object like {} or new Object()
var o2 = Object.create(Object.prototype);

// create new object which inherits properties x and y
var o3 = Object.create({x:1, y:2});


var a = {a: 1}; 
// a ---> Object.prototype ---> null

var b = Object.create(a);
// b ---> a ---> Object.prototype ---> null
console.log(b.a); // 1 (inherited)

var c = Object.create(b);
// c ---> b ---> a ---> Object.prototype ---> null

var d = Object.create(null);
// d ---> null
console.log(d.hasOwnProperty); // undefined, because d doesn't inherit from Object.prototype

Objects created with Object.create

Querying

and

Setting

Properties

Querying properties

to obtain the value of a property

the dot (.) or square bracket ([ ]) operators need to be used


the left-hand side should be

an expression whose value is an object


if using the dot operator, the right-hand

must be a simple identifier that names the property

 

if using square brackets, the value within the brackets

must be an expression that evaluates to a string

that contains the desired property name

( or a value that can be converted to a string )

Creating & Setting

Properties

to create or set a property

dot or square brackets are used

(as done when querying the property)

 

but

 

on the left-hand side of an assignment expression

 

etc etc .... pui tu alte exemple, si mai complexe :D

// get the "author" property of the book object
var author = book.author;

// get the "surname" property of the author object
var name = author.surname;
var name = book.author.surname;

// get the "main title" property of the book object
var title = book["main title"];



// create a "edition" property for the book object
book.edition = 6;

// set the "main title" property
book["main title"] = "JavaScript Basics"

object.property

similar to syntax used to access static field of a structure

 

object["property"]

looks like array access, but to an array indexed by strings,

also known as associative array (hash / map / dictionary)

 

if both expressions have the same value...

why are there two ways of accessing properties?

Objects as

Associative Arrays

object.property

 

 

in C, C++, Java, and similar strongly typed languages

an object can have only a fixed number of properties

and the names of these properties must be defined in advance

 

so using the dot and an identifier

is like the syntax used to access a static field

 

identifiers must be typed literally, they are not a datatype,
so they cannot be manipulated by the program

 

object["property"]

 

JavaScript is a loosely typed language, so a program

can create any number of properties in any object (at any time ?)

 

when accessing a property of an object with the [ ] array

notation the name of the property is expressed as a string

 

strings are JavaScript datatypes, so they can be manipulated and created while a program is running (dynamic)

 

using strings provides the flexibility

of accessing properties with string expressions

Inheritance

JavaScript objects have a set of own properties

and

also inherit a set of properties from their prototype object

 

when querying a property of an object, an own property is sought

 

if the prototype object does not have an own property by that name, but has a prototype itself, the query is performed on the prototype

 

this continues (through the prototype chain) until the property is
found or until an object with a null prototype is searched

// Let's assume we have an object o with its prototype chain looking like:
// {a:1, b:2} ---> {b:3, c:4} ---> null
// 'a' and 'b' are o own properties.

// In this example, someObject.[[Prototype]] will designate the prototype of someObject.
// This is a pure notation (based on the one used in the ECMAScript standard) and cannot be used in scripts.
// The equivalent property to use in scripts is called "__proto__" as in someObject.__proto__

console.log(o.a); // 1
// Is there an 'a' own property on o? Yes and its value is 1

console.log(o.b); // 2
// Is there a 'b' own property on o? Yes and its value is 2
// The prototype also has a 'b' property, but it's not visited. This is called "property shadowing"

console.log(o.c); // 4
// Is there a 'c' own property on o? No, check its prototype
// Is there a 'c' own property on o.[[Prototype]]? Yes, its value is 4

console.log(o.d); // undefined
// Is there a 'd' own property on o? No, check its prototype
// Is there a 'd' own property on o.[[Prototype]]? No, check its prototype
// o.[[Prototype]].[[Prototype]] is null, stop searching, no property found, return undefined

Inheritance..modifci tu exemplul

JavaScript does not have "methods" in the form that

class-based languages define them

 

any function can be added to an object in the form of a property

 

an inherited function acts just as any other property, including property shadowing (in this case, a form of method overriding)

 

when an inherited function is executed, the value of this

points to the inheriting object, not to the prototype object where the function is an own property

Inheriting "methods"

 

the fact that inheritance occurs when querying properties but not when setting them is a key feature of JavaScript because it allows to selectively override inherited properties

explicatii & exemple bune http://phrogz.net/js/classes/OOPinJS.html

Performance

the lookup time for properties that are high up on the prototype chain can have a negative impact on performance, and this may be significant in code where performance is critical

 

additionally, trying to access nonexistent properties will always traverse the full prototype chain

 

also, when iterating over the properties of an object, every property that is on the prototype chain will be enumerated

 

to check whether an object has a property defined on itself and not somewhere on its prototype chain, it is necessary to use the hasOwnProperty method which all objects inherit from Object.prototype

 

hasOwnProperty is the only thing in JavaScript which deals with properties and does not traverse the prototype chain

 

! it is not enough to check whether a property is undefined

the property might very well exist, but its value just happens to be set to undefined

Performance

Bad Practice

one mis-feature that is often used is to extend Object.prototype or one of the other built-in prototypes

 

this technique is called monkey patching and breaks encapsulation

 

while used by popular frameworks such as Prototype.js, there is still no good reason for cluttering built-in types with additional non-standard functionality

 

the only good reason for extending a built-in prototype is to backport the features of newer JavaScript engines (for example Array.forEach, etc.)

 

! so native prototypes should never be extended unless it is for the sake of compatibility with newer JavaScript features

Made with Slides.com