[英]Is this a naming convention or a function declaration
I am learning javascript and now started with objects and basic functions. 我正在学习javascript,现在开始使用对象和基本功能。 I came across this type of code and was wondering what exactly is this
我遇到了这种类型的代码,并想知道究竟是什么
var stringFunction = function(){};
stringFunction.test1 = function(){
console.log("Test 1");
}
does test1 is a part of stringFunction or just a naming convention.Thanks in advance test1是stringFunction的一部分还是只是一个命名约定。提前谢谢
function
instances are sort of "weird" in Javascript as they are objects but their typeof
is "function"
and not "object"
. function
实例在Javascript中有点“奇怪”,因为它们是对象,但它们的typeof
是"function"
而不是"object"
。
They can however have properties added and accessed using either the syntax fx
or f["x"]
. 但是,它们可以使用语法
fx
或f["x"]
添加和访问属性。 Your code simply adds a property to a function
object (the value of the property is also a function, but that is irrelevant). 您的代码只是向
function
对象添加一个属性(属性的值也是一个函数,但这是无关紧要的)。
Here test1()
is a property (function type) of the stringFunction
var. 这里
test1()
是stringFunction
var的属性(函数类型)。
So you defined a function in a function object. 所以你在函数对象中定义了一个函数。
You can use it by invoking stringFunction.test1();
您可以通过调用
stringFunction.test1();
来使用它stringFunction.test1();
as you can invoke the outer function : stringFunction();
因为你可以调用外部函数:
stringFunction();
var stringFunction = function(){console.log("Test stringFunction")};
stringFunction.test1 = function(){
console.log("Test 1");
}
stringFunction();
stringFunction.test1();
OUTPUT : 输出:
Test stringFunction
测试stringFunction
Test 1
测试1
in JavaScript every function is a Function Object. 在JavaScript中,每个函数都是一个Function Object。 see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function .
请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function 。 In you sample the code create a property 'test1' on object stringFunction.
在您的示例中,代码在对象stringFunction上创建属性“test1”。 The new property is itsealf a Function Object.
新属性是itsealf一个Function对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.