I am trying to mock inheritance in Javascript using prototype.
I have a function named Model and a type of model => Item.
JavaScript
x
12
12
1
var Model = function() {
2
this.names = ["name1", "name2"];
3
}
4
Model.prototype.Item = function(args) {
5
this.init = function(item_name) {
6
this.names[0] = item_name; // ERROR: Cannot set property '0' of undefined
7
}
8
}
9
var m = new Model();
10
var i = new m.Item();
11
i.init("New Name"); // ERROR: Cannot set property '0' of undefined
12
How can I access names
array from init()
function above?
Advertisement
Answer
Inheritance in Javascript is tricky! Read this post for a great explanation of traditional object oriented inheritance in Javascript: http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/.
JavaScript
1
35
35
1
var Model = function () {
2
this.names = ["name1", "name2"];
3
};
4
5
var Item = function () {
6
//When inheriting in Javascript you must
7
//call the inherited function's constructor manually.
8
Model.call(this);
9
};
10
11
//Inherit Model's prototype so you get all of Model's methods.
12
Item.prototype = Object.create(Model.prototype);
13
Item.prototype.constructor = Item;
14
15
Item.prototype.init = function (item_name) {
16
this.names[0] = item_name;
17
};
18
19
var Employee = function () {
20
Model.call(this);
21
};
22
23
Employee.prototype = Object.create(Model.prototype);
24
Employee.prototype.constructor = Employee;
25
26
var myItem = new Item();
27
myItem.init("New Name");
28
//prints New Name, name2
29
console.log(myItem.names);
30
31
32
var myEmployee = new Employee();
33
//prints name1, name2
34
console.log(myEmployee.names);
35
Analogous code in a more traditional object oriented language (C#):
JavaScript
1
33
33
1
public class Model
2
{
3
public Model()
4
{
5
this.Names = new[] {"name1", "name2"};
6
}
7
public string[] Names { get; set; }
8
}
9
10
public class Item : Model
11
{
12
public Item() : base() { }
13
14
public void init(string item_name)
15
{
16
this.Names[0] = item_name;
17
}
18
}
19
20
public class Employee : Model
21
{
22
public Employee() : base() { }
23
}
24
25
var myItem = new Item();
26
myItem.init("New Name");
27
//prints New Name, name2
28
Console.WriteLine(String.Join(",", myItem.Names));
29
30
var myEmployee = new Employee();
31
//prints name1, name2
32
Console.WriteLine(String.Join(",", myEmployee.Names));
33