Reputation: 61
I am not sure about differences between object literal and constructor function.
function user() {
this.name="john"
this.getName=function (){
return this.name;
};
}
var johnUser=new user();
console.log(johnUser.getName()); // Will console john
What if I want to call getName
without creating any objects something like in Java static method/function?
If I can add
user.sayName=function() {
console.log("Hey there");
}
console.log(user.sayName()); //will console Hey there.
How I can access constructor function properties?
Upvotes: 0
Views: 3001
Reputation: 191
function user() {
this.name = 'john';
}
user.prototype.getName = function(){ return this.name; }
var johnUser = new user();
console.log( johnUser.getName() ) // john
console.log( user.prototype.getName()); // undefined
user.prototype.getName = function(){ return 'just a string' }
console.log( johnUser.getName() ) // just a string
console.log( user.prototype.getName());// just a string
user.prototype.getName = function(){ return this.name || 'just a string'; }
console.log( johnUser.getName() ) // john
console.log( user.prototype.getName());// just a string
Upvotes: 0
Reputation: 723
Object literal
var user = {
name: "John",
getName: function(){
return this.name;
}
};
Alternatively, this approach won't define an object.
function sayName()
{
return "just a string";
}
Upvotes: 0
Reputation: 463
The answer is You can't. You should have read about how context of function works in JS.
When You are using new operator, empty object is being passed as context, that's why You can assign properties of this (which is reference to function context)
When You are calling a function without new operator, context of Your function is eiter global object (window) or undefined. You can print this in function to see what context You have ATM.
What You (probably) want is to create an prototype
Upvotes: 2