Home > Enterprise >  Object.Function (* is not a function)
Object.Function (* is not a function)

Time:05-23

How do i add a function after an object, without the error 'substr is not a function'

e.g.

    var country = {
        get: function() {
            return 'USA';
        },
        set: function(value) {
            
        }
    }

    console.log(country.substr(0, 2));

CodePudding user response:

You are trying to use substr() in an object that only has .get() and .set(). susbtr() is a method of string, so you can chain it after .get() that actually returns a string:

var country = {
        get: function() {
            return 'USA';
        },
        set: function(value) {
            
        }
    }

    console.log(country.get().substr(0, 2));

CodePudding user response:

I am not sure what you mean add a function after an object. But if you want to log the substring of "USA", you are missing the call of the function in your log. Country is an object. It does not have any function substring. You have to define it first. You should call get() function to retrieve the value. It should be:

country.get().substr(0, 2)

CodePudding user response:

Country is an object, you can't use substring on an object.

You could do

country.get().subsring(0,2)

On another note, this is very un-javascript like code. Looks like you're trying todo OO programming in javascript.

  • Related