簡體   English   中英

jQuery從對象創建原型

[英]jquery create prototype from object

創建原型時我想作弊

例如

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;
}

問題是“這個”指的是每個功能,而不是實際的人,您可以將其更改為箭頭功能,它將起作用

 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM