简体   繁体   English

JavaScript对象传递参数

[英]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. 这似乎是一个简单的问题,但是我对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. 在这里,您有一个教程,因此您可以更好地了解如何在JScript中使用对象。我对JScripts有点生锈,因此上周阅读了该教程,它对我有很大帮助。

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 . 您可以从MDN Docs中了解有关函数和JavaScript中的对象的更多信息。

I guess a getter for constructor function is what you need: 我猜你需要构造函数的getter

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 . 请注意,创建foo后不能将value设置为getNLog The article linked above explains also, how to set a value to getNLog . 上面链接的文章还说明了如何为getNLog设置值。

A live demo at jsfiddle . jsfiddle上的现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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