-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathConstructors.js
More file actions
79 lines (41 loc) · 1.83 KB
/
Copy pathConstructors.js
File metadata and controls
79 lines (41 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Constructors
// Constructors in JavaScript are yet again different from many other languages. Any function call that is preceded by the new keyword acts as a constructor.
// Inside the constructor - the called function - the value of this refers to a newly created object.
// The prototype of this new object is set to the prototype of the function object that was invoked as the constructor.
// Inside the constructor - the called function - the value of this refers to a newly created object. The prototype of this new object is set to the
// prototype of the function object that was invoked as the constructor.
// If the function that was called has no explicit return statement, then it implicitly returns the value of this - the new object.
function Person(name) {
this.name = name;
console.log(this);
}
Person.prototype.logName = function() {
console.log(this.name);
};
var sean = new Person('sean parker !');
// sean.logName();
// The above calls Person as constructor and sets the prototype of the newly created object to Person.prototype.
function Car() {
return 'ford';
// In case of an explicit return statement, the function returns the value specified by that statement, but only if the return value is an Object.
}
console.log(new Car());
// a new object, not 'ford'
function Car() {
return 'ford';
}
new Car(); // a new object, not 'ford'
function Persona() {
this.someValue = 2;
return {
name: 'Charles'
};
}
new Persona(); // the returned object ({name:'Charles'}), not including someValue
// console.log(new Persona());
// When the new keyword is omitted, the function will not return a new object.
function Pirate() {
this.hasEyePatch = true; // gets set on the global object!
}
var somePirate = Pirate(); // somePirate is undefined
// console.log(Pirate());