javascript function parameter place

How to write function(object) with 2 methods (alert and console.log) to be able to use it like this:

fname("text").alert //-now text is alerted;
fname("text").cons //-now text shows in console log. 

the methods are not important byt the way of execution. I know that it must be self invoiking function but i cant do it. I dont want to use it this way - fname.alert("text").

Greetings Kriss

Upvotes: 1

Views: 63

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318508

It's not possible in any sane way that works everywhere. The example you posted would require you to define an accessor for those properties - and that only works with modern JS engines.

Anyway, here's code that would actually do this. But please do not use this in any real application! See the last code block for a better solution

function fname(message) {
    var obj = {};
    Object.defineProperty(obj, 'alert', {
        get: function() {
            alert(message);
        }
    });
    Object.defineProperty(obj, 'cons', {
        get: function() {
            console.log(message);
        }
    });
    return obj;
}

This works because fname('hello').alert will cause the getter function for the alert property to be executed - and while such a function should usually return a value there's nothing to stop it from doing something like showing an alert() message.


What you could achieve in a way that works everywhere would be something like that though:

fname('text').alert();
fname('text').cons();

This could be done like this:

function fname(message) {
    return {
        alert: function() {
            alert(message);
        },
        cons: function() {
            console.log(message);
        }
    }
}

Upvotes: 5

Denys Séguret
Denys Séguret

Reputation: 382132

function fname(str) {
   return {
      alert:function(){alert(str)},
      cons:function(){console.log(str)}
   }
}

Doing fname("text").alert() alerts text.

Upvotes: 4

Related Questions