简体   繁体   English

具有多个参数的构造函数?

[英]Constructor function with multiple parameters?

The constructor example I see a lot is 我看到的构造函数示例很多

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
    this.nationality = "English";
}

But what if you want many parameters, like 20+. 但是,如果您想要许多参数,例如20+,该怎么办? This seems like it would be inefficient. 这似乎是低效的。 What would be the correct and efficient way of declaring a constructor function that takes in many parameters? 声明一个包含多个参数的构造函数的正确有效的方法是什么?

My end goal is to create an image slider with a lot of user settings (slidesToShow, slidesToScroll, slideClass, etc). 我的最终目标是创建具有许多用户设置(slidesToShow,slidesToScroll,slideClass等)的图像滑块。 So I am looking to have the user initialize it like and provide options. 因此,我希望用户能够对其进行初始化并提供选项。 The way I have it now is kind of weird lol. 我现在拥有它的方式有点奇怪。 example: 例:

function Slider(options) {
 const slideClass = options.slideClass
}

and then it is initialized like so: 然后像这样初始化它:

const demoSlider = new Slider({
 slideClass: 'image-slider'
})

But I am not using the this keyword like a normal constructor function and yet it is not a object literal either. 但是我没有像普通的构造函数那样使用this关键字,但是它也不是对象文字。 So my code must just be built wrong? 所以我的代码一定是错误的吗? Just switched from mainly jQuery trying to learn/write vanilla JS the right way. 刚从主要是jQuery切换为尝试以正确的方式学习/编写普通JS。

Thanks for any help in advance! 感谢您的任何帮助!

Either just store an object under this.options : 要么只是在this.options下存储一个对象:

 function Slider(options) {
    this.options = options;
 }

Or if you want it directly under this , just use Object assign: 或者,如果您想直接在this下使用,则只需使用Object Assign:

 function Slider(options) {
   Object.assign(this, options);
    console.log(this.name);
 }

 new Slider({ name: "test" });

I think you better set them one by one, because they might have default value, ex: 我认为您最好将它们一一设置,因为它们可能具有默认值,例如:

this.height = (options.height)?options.height:100;

Also I think you're not quite understand the meaning of new . 另外我认为您不太了解new的含义。

You didn't use this which means all variables are in your function, 您没有使用this ,这意味着所有变量都在您的函数中,

maybe in this case you only need to execute that function once to init your slider's event. 也许在这种情况下,您只需要执行一次该函数即可启动滑块事件。

so you only need to call Slider(options) . 因此,您只需要调用Slider(options)

new Slider() will create a Object that can be reuse, new Slider()将创建一个可以重复使用的对象,

but you didn't even assign to a var like var mySlider = new Slider() ... 但是您甚至没有分配给像var mySlider = new Slider()这样的var mySlider = new Slider() ...

You should consider in this case whether you need to design your function as a function or a constructor ? 在这种情况下,您应该考虑是否需要将函数设计为function还是constructor

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

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