Reputation: 4112
I'm quite new to both JavaScript OOP and require.js
I'm learning to use require.js to improve application scalability, I tried to google for articles but not really understand because of my poor JavaScript background.
I have come up with this coding.
define([], function() {
function Employee(empName) {
return {
_empName: empName,
getEmployeeName: function() {
return _empName;
}
}
}
});
define([], function() {
function Customer(customerName) {
this._customerName = customerName;
this.getCustomerName = function() {
return this._customerName;
}
}
return(Customer);
});
I have tried 2 different styles of coding for Employee and Customer prototype.
require(['customer', 'employee'], function(Customer, Employee) {
c = new Customer('Boy');
console.log('Customer name is ' + c.getCustomerName());
e = new Employee('Mike');
console.log('Employee name is ' + e.getEmployeeName());
});
This is the result I got.
My question is that coding in customer.js is only the way to declare prototype for using with require.js ?
My understanding is that require.js always and only inject dependencies as class (not instance) right?
Helping me by answer these 2 simple questions will help me to move along to the next step of my learning, any suggested articles would be really appreciated, (I really have no ideas which specific topics to search for).
Thanks
Upvotes: 1
Views: 280
Reputation: 664970
My question is that coding in customer.js is only the way to declare prototype for using with require.js ?
No. Using prototypes has nothing to do with using require.js.
My understanding is that require.js always and only inject dependencies as class (not instance) right?
No. It injects whatever you return from the module definition. In case of employee.js
, that is nothing; and Employee
ends up being undefined
.
So fix your employee code:
define([], function() {
function makeEmployee(empName) { // it's not a constructor - don't capitalize
// it shouldn't be invoked with `new` either
return {
_empName: empName,
getEmployeeName: function() {
return this._empName; // it's a property, not a variable
}
}
}
return makeEmployee; // return the function to become the module!
});
Upvotes: 1