john33
john33

Reputation: 61

Is it possible to call constructor function method without creating object in JS?

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

Answers (3)

MypKOT-1992
MypKOT-1992

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

Vic
Vic

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

grzesiekgs
grzesiekgs

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

Related Questions