gpt4 book ai didi

javascript - 如何从构造函数参数创建成员?

转载 作者:行者123 更新时间:2023-11-30 07:53:35 24 4
gpt4 key购买 nike

我想根据构造函数参数创建一些对象成员,但它没有按预期工作。没有创建成员。我怎样才能做到这一点?

function Foo(parameters = []) {
parameters.forEach(function(e) {
this[e.name] = e.initial;
});
};

const p = [{
"name": "sensitivity",
"initial": 50
}];

const f = new Foo(p);

最佳答案

您正在使用 this forEach 提供的回调 函数中的关键字方法,但是 this该函数只是对窗口对象的引用

您可以阅读有关 this 范围的更多信息在 javascript 中 answer.

1。使用 bind方法。

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

function Foo(parameters = []) {
parameters.forEach(function(e) {
this[e.name] = e.initial;
}.bind(this));
};

const p = [{
"name": "sensitivity",
"initial": 50
}];

const f = new Foo(p);
console.log(f);

2。使用 arrow功能。

直到 arrow函数,每个 new 函数定义了自己的this值(value)。

例如,this在构造函数的情况下可以是一个新对象。

function Person(age){
this.age=age;
console.log(this);
}
let person=new Person(22);

this可以指向base对象,如果创建的函数可以像obj.getAge()那样被访问.

let obj={
getAge:function(){
console.log(this);
return 22;
}
}
console.log(obj.getAge());

arrow函数不创建自己的 this , 它只是使用了 this enclosing 的值(value)执行context .另一方面,arrow函数使用 this父范围。

function Foo(parameters = []) {
parameters.forEach((e) => {
this[e.name] = e.initial;
});
};

const p = [{
"name": "sensitivity",
"initial": 50
}];

const f = new Foo(p);
console.log(f);

关于javascript - 如何从构造函数参数创建成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46675786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com