gpt4 book ai didi

javascript - 在功能 block 中管理特殊 "this"对象的属性

转载 作者:行者123 更新时间:2023-11-30 20:55:44 26 4
gpt4 key购买 nike

我在一个函数中得到了这段代码。

第一行有效。

    this.learningPlan.learnerType = ['abc']; // this line works

但下面的这些行不会。

    properyName = 'learningPlan.learnerType';
this[properyName] = ['abc'];

有没有办法引用 this 以便我可以将 properyName 值传递给函数?

我需要这个功能,这样我就可以保持函数的通用性,而不用提及特定的短语“learningPlan.learnerType”。因为然后我可以执行以下操作:

function blah(propertyName){
this[properyName] = ['abc'];
}

最佳答案

这看起来如何:

编辑:添加了解释性注释。

function T() {
this.learningPlan = { learnerType : "aaa" };
this.setVal = function(p, v) {
// Split the property string into its "parts"
// thus "learningPlan.learnerType" becomes ["learningPlan","learnerType"]
var ps = p.split(".");

// Remove and capture the "last" (right-most) property
// From ["learningPlan","learnerType"] this would be "learnerType"
// leaving the array with ["learningPlan"]
var lastProp = ps.pop();

// Work "down" the object finding each level object finally returning
// the property object containing the property you wish to set
var o = ps.reduce(function(a,e) {
// This checks that each object["property"] exists and if
// it doesn't then it creates an empty object so that it can
// continue traversing down the property hierarchy.
// Given the property string "learningPlan.learnerType" if the
// property this.learningPlan didn't exist then attempting to
// reference this.learningPlan.learnerType would throw an error
// since learnerType is not a property of undefined. This is, I
// believe, the error you are experiencing. Using (a[e] || {})
// ensures that a[e] references something so that traversal
// can continue.
a[e] = (a[e] || {});

// This simply returns the property so that the reduce can keep
// moving through the array
return a[e];
}, this);

// Finally, we set the value for the last property in our string.
// The above reduce would walk down 'this' finding/setting each
// property until it reached the last string we left in our array
// after the pop and thereby returning a reference to that property
// into our variable "o". We then use the last property string as a
// property of "o" to set our value.
o[lastProp] = v;
};
}

它将允许您执行以下操作:

var t = new T();
t.setVal("learningPlan.learnerType", "def");

关于javascript - 在功能 block 中管理特殊 "this"对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47686336/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com