简体   繁体   中英

JavaScript Objects passing arguments

I've been search for solution for this for quite a while now but ive not came across the yet.

This may seem like a simple question but i quite new to the objects in javascript.

My question is how do i get a get a object to pass a argument to a function.

there would be a function with an argument that console logs the argument.so

  function someFunction(arg){console.log(arg);}

and i wont to pass the augment like this :

var arg = "foo"
arg.someFunction

instead of :

someFunction(foo)

Well, I am not sure what you really want on this.

But this is not the way to go.

Here you have an tutorial so you can have a better idea in how to use Objects in JScript, I am a bit rusty in JScripts so I read that tutorial last week, and it helped me a lot.

This code you posted is a bit difficult to understand the goal, if you could clear this, I can help you better.

I'm assuming that this is what you're looking for :

var obj = function functionName(arg){
    console.log(arg)
};
var foo ="foo";
obj(foo); // will print out "foo" to the console

You could read more about Functions and about Objects in JavaScript from the MDN Docs .

I guess a getter for constructor function is what you need:

function TestObj (arg) {
    Object.defineProperty(this, 'getNLog', {
        get: function () {
            console.log(arg);
            return arg;
        }
    });
}

var foo = new TestObj('FOO');
// Usage
alert(foo.getNLog);

Notice, that you can't set value to getNLog after creating foo . The article linked above explains also, how to set a value to getNLog .

A live demo at jsfiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM