Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

原生js封装函数,如何传入参数?

image

这种封装的函数,如何把参数传进去?就是里面那个可以打印外部传入的参数,调用new Ribbons(param)这样传入。

有没有大神知道,望指教一下!谢谢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

首先 param 没有定义,会报错。你是想打印传入的参数的话:

(function (name, factory) {
    if (typeof window === "object") {
        window[name] = factory(1); // 这里传入
    }
})('Ribbons', function(param) {
    console.log(param);
});

或者

(function (name, factory) {
    if (typeof window === "object") {
        window[name] = factory(1); // 这里传入
    }
})('Ribbons', function() {
    console.log(arguments);
});

然后 function() { console.log(param) } 调用后并没有返回值,所以 window.Ribbons = undefinednew Ribbons() 又会报错。应该返回一个函数来作为构造函数:

(function (name, factory) {
    if (typeof window === "object") {
        window[name] = factory(1); // 这里传入
    }
})('Ribbons', function() {
    console.log(arguments);
    
    return function() {
        console.log(this instanceof Ribbons); // true
    };
});

new Ribbons();

期望 new Ribbons(自定义参数)

(function (name, factory) {
    if (typeof window === "object") {
        window[name] = factory();
    }
})('Ribbons', function() {
    // console.log(param); 这里会报错,并没有定义 param 变量
    
    return function(param) { // 作为构造函数
        console.log(param); // 1
    };
});

new Ribbons(1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...