4. Objects
Is a self-contained collection of data.
The data can be
properties, a variable belonging to an object.
methods, a function that the object can invoke, an
object in itself.
Properties and methods are both accessed using
dot notation.
5. Objects (Cont’d)
No class, classless approach
Objects are created through:
Literal notation using { }
Constructors function
6. Using object literal
notation{}
To create an empty object
var x={}
To create an object with properties and methods
var student={
track:"PD",
marks:[100,200,300],
getTotal: function ()
{
var sum=0;
for(var i in this.marks)
sum+=this.marks[i];
return sum;
}
}
7. Accessing Properties
Using square bracket notation
student[„track‟] PD
Using the dot notation,
student.track PD
8. Objects inside Objects
Example
var book = {
name: 'Catch-22',
published: 1961,
author: {
firstname: 'Joseph',
lastname: 'Heller'
}
};
book.author.firstname
book['author']['lastname']
10. Using Constructor function
function student(name) {
this.track="PD”;
this.name=name;
this.marks=[100,200,300];
this.getTotal= function ()
{
var sum=0;
for(var i in this.marks)
sum+=this.marks[i];
return sum;
};
}
To create an object, use new operator
var std = new student(“Smith”);
11. What happens when you
create an object without
‘new’ operator?
var std =student()
this refers to global object ‘window’
std undefined or whatever constructor returns if it
returns anything
13. constructor Property
It contains a reference to the constructor function used to
create this object.
std.constructor student(name)
var h3 = new std.constructor('Rafaello');
If an object was created using the object literal notation??
its constructor is the built-in Object() constructor function.
var o = {};
o.constructor Object() empty object
typeof o.constructor "function"
14. Passing Objects
When you copy an object or pass it to a function, you
only pass a reference to that object. Consequently, if you
make a change to the reference, you are actually
modifying the original object.
Example
var original = {howmany: 1};
var copy = original;
copy.howmany 1
copy.howmany = 100;
original.howmany 100
The same thing applies when passing objects to
functions:
15. Comparing Objects
true iff you compare two references to the
same object. >>>
var fido = {breed: 'dog'};
var benji = {breed: 'dog'};
benji == fido false
However
var mydog = benji;
mydog == benji true
16. Object object
Object is the parent of all JavaScript objects
Every object created inherits from it.
To create a new empty object
var o = {};
var o = new Object();
Properties:
o.constructor property returns the constructor function
o.toString() is a method that returns a string representation of the
object
o.valueOf() returns a single-value representation of the object, often
this is the object itself
17. Private Members
Ordinary ’var’ of the constructor are private members.
function Container(param)
{
this.member = param;
var secret = 3;
var that = this;
}
secret and that are attached to the object, but they are
not accessible to the outside, nor are they accessible to
the object's own public methods. They are accessible to
private methods.
18. Private Methods
function Container(param)
{
function dec()
{
if (secret > 0)
{
secret -= 1; return true;
}
else
{return false;}
}
this.member = param; var secret = 3; var that =
this;
}
19. Privileged Method
Is able to access the private variables and
methods, and is itself public.
this.service = function ()
{
return dec() ? that.member : null;
};
Private and privileged members can only be made
when an object is constructed (in a constructor).
20.
21. Inheritance
Used for code reuse
JavaScript don’t use class-inheritance but prototype-
inheritance (based on Objects)
There are many ways to implement inheritance.
We will cover Prototype Chaining
22. Function Object
Properties:
length: number of arguments
constructor: Function()
prototype: initially is an empty object
23. Prototype
JavaScript prototype-based object model
Every function object has a prototype property,
Initially empty Object
Augment this empty object with properties and
methods.
Only be used when function is used as a
constructor.
25. What if object contain a
property defined in
prototype?
Own Property overrides prototype property
propertyIsEnumerable()
hasOwnProperty()
isPrototypeOf()
26. What is the result?
function Gadget(name, color) var newtoy = new
Gadget('webcam', 'black');
{ for (var prop in newtoy)
this.name = name;
{
this.color = color;
console.log(prop + ' = ' +
this.someMethod =
function(){return 1;} newtoy[prop]);
}
}
name = webcam
Gadget.prototype.price = 100; color = black
someMethod = function () { return 1; }
Gadget.prototype.rating = 3; price = 100
rating = 3
27. What is the result?
function var newtoy = new
Gadget(name, color) Gadget('webcam', 'black');
{ for (var prop in newtoy) {
this.name = name; if (newtoy.hasOwnProperty(prop))
this.color = color; {
this.someMethod = console.log(prop + '=' +
function(){return 1;} newtoy[prop]);
} }
}
Gadget.prototype.price =
100; name = webcam
Gadget.prototype.rating = 3; color = black
someMethod = function () { return 1; }
28. Augmenting Built-in
Objects
Array.prototype.inArray = function(needle) {
for (var i = 0, len = this.length; i < len; i++) {
if (this[i] === needle) {
return true;
}
}
return false;
}
30. function Shape(){
this.name = 'shape';
this.toString = function()
{return this.name;};
}
function TwoDShape(){
Inheritance is done through:
this.name = '2D
shape'; TwoDShape.prototype
} = new Shape();
function Triangle.prototype =
Triangle(side, height) { new TwoDShape();
this.name = 'Triangle';
this.side = side;
this.height = height;
this.getArea =
function(){return this.side *
this.height / 2;};
}
31. Note
When you completely overwrite the
prototype,
Has negative side effects on the constructor
property.
Solution:
TwoDShape.prototype.constructor =
TwoDShape;
Triangle.prototype.constructor = Triangle;
32. What do the JavaScript
engine does when you call
my.toString()?
var my=new Triangle(5,10)
Loops through all of the properties of my
If not found, looks at the object that my.__proto__
points to; the instance of TwoDShape() .
Loops through the instance of TwoDShape.
If not found, checks the __proto__ of that object that
points to the instance of Shape().
Loops through the instance of Shape() and toString()
is finally found!
33. For efficiency:
Moving shared properties to the
prototype
function Shape(){} function Triangle(side, height) {
Shape.prototype.name = 'shape'; this.side = side;
Shape.prototype.toString = function() this.height = height;
{return this.name;}; }
function TwoDShape(){} Triangle.prototype = new
TwoDShape.prototype = new TwoDShape();
Shape(); Triangle.prototype.constructor =
TwoDShape.prototype.constructor = Triangle;
TwoDShape;
TwoDShape.prototype.name = '2D Triangle.prototype.name = 'Triangle';
shape'; Triangle.prototype.getArea =
function(){return this.side *
this.height / 2;};
34. References
Object-Oriented JavaScript Create Scalable, reusable, high
quality JavaScript applications and libraries, Stoyan
Stefanov, 2008.
http://www.quirksmode.org/js
Hinweis der Redaktion
By convention, we make a private ‘that’ variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification, which causes this to be set incorrectly for inner functions (private methods).Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.
var newtoy = new Gadget('webcam', 'black');newtoy.name;"webcam"newtoy.color;"black"newtoy.whatAreYou();"I am a black webcam"newtoy.price;100newtoy.rating;3newtoy.getInfo();"Rating: 3, price: 100"
var a = ['red', 'green', 'blue'];a.inArray('red');truea.inArray('yellow');false
Instead of augmenting an object with individual properties or methods we can specify another object as the prototype object. Thus, making an object inherit all properties of another object.
isPrototypeOf() to check whether an object inherits another or no