我想在创建原型时作弊
例如
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;
}
你的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];
}
}
问题是“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);
使用bind
获得正确的范围
function Person(args) {
$.each(args, function(key, value) {
this[key] = value;
}.bind(this)); //Use bind for getting the right scope
}