javascript - 仅通过传递属性来修改 JS 对象的属性?

标签 javascript jquery

我正在构建一个接受两个参数的插件 - 高度和宽度。该插件的使用者可能有一个矩形对象,或正方形对象,或多边形对象等。它们的宽度/高度的名称可能不同:

var square = { 
   width: 200,
   height: 200
}

var rectangle = { 
   Width: 200,
   tall: 200
}

var polygon = { 
   w: 200,
   h: 200
}

我正在尝试构建一个接受宽度/高度参数并修改它们的函数,以便更新父对象。像这样的事情:

var alterStuff = function (width, height){
    width = 200;
    height = 200;
};

var obj = {width: "28", height: "34"};

alterStuff(obj.width, obj.height);

alert(obj.width);

目标是使用者可以传入两个原始类型,并且 alterStuff 函数将在对象上更新它们。

可以使用什么模式来实现这一目标?现在 obj 属性尚未更新 - 我在警报中看到“28”,但我希望在不传入对象的情况下看到“200”,因为我不知道什么是在所有情况下,属性名称都将位于该对象上。

最佳答案

简短回答:你不能!

当您将某些内容传递给函数时,您传递的是它的值。如果它是原始值,例如 5,则将 5 传递给函数。如果它是一个对象,实际上它是对对象的引用,并且您传递该引用。这意味着当您传递具有例如 45px 值的 obj.width 时,您仅将该字符串传递给函数,并且绝对没有与 obj< 的连接.

更新对象属性的唯一方法是传递对象本身和属性名称:

function change(obj, key, val) {
  obj[key] = val;
}

var obj = { width : 5 };
change(obj, 'width', 10);
<小时/>

在您的特定情况下,您可以尽力从对象的键“猜测”属性名称。在下面的示例中,widthKey 和 heightKey 是可选的,因此如果库函数的用户有一个行为良好的对象,则不需要传递它们。否则,他应该通过它们。

function updateSize(object, width, height, opt_widthKey, opt_heightKey) {
  // potential width properties:
  var widths = ['width', 'Width', 'w'];
  // potential height properties:
  var heights = ['height', 'Height', 'h'];

  var widthKey = opt_widthKey || getPropertyName(object, widths);
  if (!widthKey) throw new Error('Can not guess width property');

  var heightKey = opt_heightKey || getPropertyName(object, heights);
  if (!heightKey) throw new Error('Can not guess height property');

  object[widthKey] = width;
  object[heightKey] = height;
}

function getPropertyName(object, properties) {
  for (var i=0; i<properties.length; i++) {
    if (object.hasOwnProperty(properties[i]))
      return properties[i];
  }
}

// usage:

var obj = { width : 5, Height : 10 };
var notGood = { tall : 20, wide : 40 };

updateSize(obj, 100, 200);
updateSize(notGood, 100, 200, 'wide', 'tall');

关于javascript - 仅通过传递属性来修改 JS 对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21884815/

相关文章:

javascript - CSS 对齐问题

javascript - 通过浏览器扩展在网络上每个页面的顶部插入一个栏

javascript - 视差效果使元素跟随滚动延迟

jquery - 日期范围选择器显示不正确的时间

javascript - jquery 根据浏览器宽度改变

javascript - 尝试从 Vimeo URL 解析 ID 时出现问题

javascript - 为什么我的if不传入else呢?

jquery - css - 在内容上方 float 页眉和页脚,使用 jquery 自动调整背景大小

javascript - 如何修复 Window.getComputedStyle 不是对象错误

javascript - 剑道网格批量编辑