Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/453.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,因此,我可以从外部定义函数的属性,例如:createNewPerson.hmm=3

因此,我可以从外部定义函数的属性,例如:
createNewPerson.hmm=3
完整代码:

function createNewPerson(name) {
//var hello = "hgfgh";
//hello: "hgfgh"
//hello = hgfgh;
//this.hello = hgfgh;

}
createNewPerson.hmm = 3;
alert(createNewPerson.hmm);
alert(createNewPerson.hello);

您好,请尝试下面的代码


我认为您正在尝试创建对象。在javascript中,您可以这样做:

function Test(){
  this.foo = "bar";
  this.func = function(){
    console.log(this.foo);
  }
}

const test = new Test();
test.foo = "baz";
test.func(); //Will print "baz".

注意“new”的用法。这就是允许代码修改对象属性的机制。修改后的属性值可由对象本身访问。

您可以使用
createNewPerson.hmm=“something”(甚至从函数内部)。但是如果函数是匿名的,那么情况就不同了。
this.hello
是正确的语法,但是您需要创建一个实例
newcreatenewperson()
@RobbieMilejczak:No;他不是这么做的。如果没有命名函数,以前会有一个
参数.callee
选项。Robbie:如果不使用
new
来创建对象,函数中的
这个
实际上指向全局对象,因此
createNewPerson.hello
仍然是未定义的。
function Test(){
  this.foo = "bar";
  this.func = function(){
    console.log(this.foo);
  }
}

const test = new Test();
test.foo = "baz";
test.func(); //Will print "baz".