Null对象中属性默认值的赋值

Assignment of Property Default Values in a Null Object Javascript

本文关键字:赋值 默认值 属性 对象 Null      更新时间:2023-09-26

我有这个对象TrSet,它从dom中获取节点。有时这些dom元素可以为null,我想处理节点的属性,不幸的是,我不知道如何在undefined属性上使用null条件赋值。

var TrSet = function(valid,stat,txt,dd){
     this.validateField = valid || "";
     this.statusDropDown = stat || "";
     this.txtValue = txt || "";
     this.ddValue = dd || "";
     this.txtValue.value = txt.value || ""; //Cannot read property value of undefined
     this.ddValue.style.visibility = dd.style.visibility || "hidden"; //same
     this.validate = function () {
         /// Even when attempting to access 
         /// the property with hasOwnProperty throws the error 
         ///"Cannot read property 'hasOwnProperty' of null"!
       if (this.statusDropDown.hasOwnProperty("value") && this.validateField.hasOwnProperty("style")) {

我不明白为什么这两个都失败了。如果它为空或未定义,它应该对空字符串求值为true,并将其设置为等于该值。

EDIT For Clarity

在第一个例子中

var TrSet = function(txt) {
    this.txtValue = txt || "";
    this.txtValue.value = txt.value || "";
}

如果txt为空则设其等于"",如果txt.value为空则设其等于""。这是怎么失败的?

第二个例子

var TrSet = function(stat) {
    this.statusDropDown = stat || "";
    if (this.statusDropDown.hasOwnProperty("value")) { }

如果stat为空,则设置statusDropDown等于""。然后我检查它是否为hasOwnProperty。为什么会失败呢?

我不明白为什么这两个都失败了。如果它为空或未定义,它应该对空字符串求值为true,并将其设置为等于该值。

不完全是这样:语句txt || ""返回 txt""的值,以先为真者为准。它不会在任何地方赋值,特别是不会赋值给txt。你单独分配。

因此,在你的例子中(例如,减少到必要的部分):

var TrSet = function(valid,stat,txt,dd){
  this.txtValue = txt || "";
  console.log('txt will still be undefined but txtValue will not be', txt, this.txtValue);
  this.txtValue.value = txt.value || "";
}

要达到预期效果,需要再次默认设置txt,如下所示:

var TrSet = function(valid,stat,txt,dd){
  this.txtValue = txt || "";
  console.log('txt will still be undefined but txtValue will not be', txt, this.txtValue);
  this.txtValue.value = (txt || "").value || ""; // <- change here
}

当然,这在很大程度上是不可读的(.value || ''如何组?你一眼就知道吗?),所以我们可能会缓存它:

var TrSet = function(valid,stat,txt,dd){
  var realTxt = txt || ""
  this.txtValue = realTxt;
  this.txtValue.value = realTxt.value || "";
}

现在,这是可行的,但还不够理想。ES6增加了直接在参数列表中提供默认值的功能,这样更简洁:

var TrSet = function(valid = "", stat = "", txt = "", dd = "") {
  this.txtValue = txt;
  this.txtValue.value = txt.value || "";
}

直接回答你添加的两个简短的问题:

var TrSet = function(txt) {
  this.txtValue = txt || "";
  this.txtValue.value = txt.value || "";
}

如果txt为空,设置它等于",如果txt。值为空,设置它等于"。这是怎么失败的?

因为txt || "" 没有赋值给txt,它只是返回 txt "",返回值赋值给this.txtValue

var TrSet = function(stat) {
  this.statusDropDown = stat || "";
if (this.statusDropDown.hasOwnProperty("value")) { }

如果stat为null,则设置statusDropDown等于"。然后检查它是否有ownproperty。为什么会失败呢?

可能是因为this没有绑定,所以它实际上没有statusDropDown的值。在JavaScript中,this可以根据函数的调用方式而改变。

这一行:

this.txtValue.value = txt.value || "";

txtnull,尝试在null对象上引用属性会导致错误。你需要把它改成:

this.txtValue.value = txt ? (txt.value || "") : "";

在解引用变量之前测试它是否为空。