Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/454.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中为自定义对象创建属性?_Javascript - Fatal编程技术网

如何在JavaScript中为自定义对象创建属性?

如何在JavaScript中为自定义对象创建属性?,javascript,Javascript,我知道我可以为自定义对象创建函数,如 var newObj = { myFunc1: function () { alert('hello'); }, myFunc2: function () { alert('hello'); } } 现在,我如何创建一个新属性,以便在myFunc1或myFunc2中设置该属性,然后后者通过执行newObj.myProperty来使用该属性。如果我正确地解释了这篇文章,那么您可以这样做: var ne

我知道我可以为自定义对象创建函数,如

var newObj = {
    myFunc1: function () {
        alert('hello');
    },
 myFunc2: function () {
        alert('hello');
    }
}

现在,我如何创建一个新属性,以便在myFunc1或myFunc2中设置该属性,然后后者通过执行newObj.myProperty来使用该属性。

如果我正确地解释了这篇文章,那么您可以这样做:

var newObj = {
    myFunc1: function () {
        this.greeting = "hello";
    },
    myFunc2: function () {
        alert(this.greeting);
    }
};

newObj.myFunc1(); // set the property on newObj
newObj.myFunc2(); // alert the property on newObj

alert(newObj.greeting); // access it directly from the object
var newObj = {
    propertyHere: "Here's a property.", // custom property
    myFunc1: function () {
        newObj.propertyHere = "Here's a changed property."; // set property
    },
    myFunc2: function () {
        alert(newObj.propertyHere); // get property
    }
}

如果我对这篇文章的理解正确,那么你可以这样做:

var newObj = {
    propertyHere: "Here's a property.", // custom property
    myFunc1: function () {
        newObj.propertyHere = "Here's a changed property."; // set property
    },
    myFunc2: function () {
        alert(newObj.propertyHere); // get property
    }
}

您不必为对象显式定义新属性。只需在函数内部使用this.yourNewProperty=“blablabla”。但是,在对象描述的开头显式定义它是一种很好的做法,如
yourNewProperty:,
(使用任何需要的伪值代替“”),因为它确实提高了代码的可读性。

您不必为对象显式定义新属性。只需在函数内部使用this.yourNewProperty=“blablabla”。但是,最好在对象描述的开头明确定义它,如
yourNewProperty:,
(使用所需的任何伪值代替“”),因为它确实可以提高代码的可读性。

对象上的函数可以通过
this
关键字访问其其他属性

var newObj = {
                foo : 'Hello There',
                displayValue: function() { alert(this.foo); },
                changeValue: function() { this.foo = 'Goodbye world'; }
             }


newObj.displayValue();
newObj.changeValue();
newObj.displayValue();

这将显示“Hello There”,后跟“再见世界”

对象上的函数可以通过
This
关键字访问其其他属性

var newObj = {
                foo : 'Hello There',
                displayValue: function() { alert(this.foo); },
                changeValue: function() { this.foo = 'Goodbye world'; }
             }


newObj.displayValue();
newObj.changeValue();
newObj.displayValue();
这将显示“Hello There”,后跟“再见世界”