gpt4 book ai didi

javascript - jquery 从对象创建原型(prototype)

转载 作者:行者123 更新时间:2023-11-28 12:14:46 25 4
gpt4 key购买 nike

我想在创建原型(prototype)时稍微作弊

例如

var person = {
name: 'John',
age: 110,
gender: 'm',
...
};

var employee = new Person(person);

function Person(args) {
$.each(args, function(key, value) {
this[key] = value; // Cannot create property 'key' on number
});
}

console.log(employee.age);

在 PHP 中可以这样做

function __construct() {
$args = func_get_arg(0);
foreach ($args as $key => $value) {
$this->$key = $value;
}
return $this;
}

最佳答案

问题是“this”指的是每个函数而不是实际的 Person您可以将其更改为箭头功能,它将起作用

var person = {
name: 'John',
age: 110,
gender: 'm',
...
};

var employee = new Person(person);

function Person(args) {
$.each(args, (key, value) => { //changed to arrow function to keep this in the same scope
this[key] = value; // Cannot create property 'key' on number
});
}

console.log(employee.age);

关于javascript - jquery 从对象创建原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52003602/

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