jQuery从对象创建原型

时间:2018-08-24 11:35:32

标签: javascript jquery 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;
}

3 个答案:

答案 0 :(得分:3)

问题是“ 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);

答案 1 :(得分:2)

您的jQuery代码上的问题是,“ this”实际上在每个作用域的jquery中,因此要对新实例进行实际原型制作,您需要执行以下操作:

var dictionary = new Dictionary<string, List<object>>();

for (int i = 1; i <= 2; i++)
{
    if (!dictionary.TryGetValue("Key1", out List<object> list))
    {
        list = new List<object>();
        dictionary["Key1"] = list;
    }

    list.Add(i);
}

您也可以在不使用jQuery的情况下实现这一目标:

function Person(args) {
    var _this = this;
   $.each(args, function(key, value) {
      _this[key] = value;
   });
}

答案 2 :(得分:1)

使用bind获取正确的范围

function Person(args) {
   $.each(args, function(key, value) {
      this[key] = value; 
   }.bind(this)); //Use bind for getting the right scope
}