我想在创建原型时作弊一点
例如
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"指的是每个函数而不是实际的人 您可以将其更改为箭头功能,它将起作用
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);
jQuery 代码的问题在于"this"实际上在每个 jquery 范围内,因此要实际制作新实例的原型,您需要这样做:
function Person(args) {
var _this = this;
$.each(args, function(key, value) {
_this[key] = value;
});
}
你也可以在不使用jQuery的情况下实现这一点:
function Person(args) {
for(var key in args){
this[key] = args[key];
}
}
使用bind
获取正确的范围
function Person(args) {
$.each(args, function(key, value) {
this[key] = value;
}.bind(this)); //Use bind for getting the right scope
}