如何在Javascript中传递对象作为参数?

Mod*_*ner 3 javascript parameters jquery function object

我在这里找到了一些与我的问题相关的问题,但没有得到我正在寻找的答案.我想做这样的事情,类似于jQuery经常做的事情:

createCSS("mystyle.css", {
    media: "screen",
    type: "text/css"
});
Run Code Online (Sandbox Code Playgroud)

我试过这个来完成我想要的但是它不起作用:

var prop = {
    media: '',
    type: ''
};

function createCSS(href, prop) {
    var anchor = document.createElement("link");
    anchor.setAttribute("href", href);
    anchor.setAttribute("media", prop.media);
    anchor.setAttribute("type", prop.type);

    if(typeof anchor != "undefined") {
        document.getElementsByTagName("head")[0].appendChild( anchor );
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我知道我可以创建单个多个参数,createCSS("mystyle.css", "screen", "text/css");但我不喜欢它,另一种方式看起来更酷.

很多新的JavaScript,所以任何帮助将非常感谢!

bfa*_*tto 10

您不必声明/初始化var prop.你的函数看起来很好,只需调用它传递一个对象prop,就像在你自己的例子中一样:

createCSS("mystyle.css", {
    media: "screen",
    type: "text/css"
});
Run Code Online (Sandbox Code Playgroud)

如果部件的意图var prop是避免分配undefined属性,则需要在函数内部进行一些调整:

function createCSS(href, prop) {
    prop = (typeof prop !== "object") ? {} : prop;
    prop.media = prop.media || 'screen';  // default media will be screen
    prop.href = prop.href || 'text/css';  // default type will be text/css
    // rest of code
}
Run Code Online (Sandbox Code Playgroud)

我建议的一些小改进:

  • 您的变量anchor不包含anchor(<a>)元素.为什么不打电话呢link
  • 你似乎不需要if(typeof anchor != "undefined")条件.因为你正在创建上面几行的元素,所以该变量永远不会被定义.你可以跳过ifappendChild直接.