javascript将属性添加到函数 [英] javascript adding property to function
问题描述
函数Rabbit(){
console.log(shiv);
$ / code $ / pre
现在不用创建这个函数的对象,我可以指定这个对象的属性 Rabbit.bark =函数(行){
console.log(name is,line);
};
这是什么意思。这样做是否会添加变量树皮来实现功能。或者这是否添加属性到 Rabbit
对象,即使我没有使用 new
运算符创建一个对象。 / p>
解决方案 功能在JavaScript中只是一个对象,它被称为 Function object。
就像任何其他类型的对象一样,它有自己的构造函数( new Function(...)
),方法( apply
, bind
, call
...)和属性( arguments code>, caller
, name
...)。 查看文档。
您可能熟悉如下创建函数:
函数Rabbit(){
console.log('shiv');
}
然后你应该知道你也可以创建一个这样的函数: p>
var Rabbit = new Function('console.log(shiv)');
现在,您可能会猜出来。如果您向Function对象添加新属性,只要不覆盖现有的函数,该函数仍然可以正常工作。
这样做是否可以将变量树皮添加到函数中?
- 该函数具有自己的闭包,向函数添加变量的唯一方法是使用
Rabbit.bind(object)将该文件绑定到 this
/ code>
是否为Rabbit对象添加了一个属性
- 好吧,由于兔子对象只是一个对象,所以是。
Let us say we have a function.
function Rabbit(){
console.log("shiv");
}
Now without creating an object of this function i can assign the property of this object
Rabbit.bark = function(line) {
console.log("name is", line);
};
What does this mean. do this add a variable bark to function. or does this add a property to Rabbit
object, even if I am not creating an object using the new
operator.
解决方案 Function in JavaScript is just an object, it is called Function object.
And just like any other types of object, it has its own constructor (new Function(...)
), methods (apply
, bind
, call
...) and properties (arguments
, caller
, name
...) . See the document.
You might be familiar with creating a function like this:
function Rabbit() {
console.log('shiv');
}
Then you should know that you can also create a function like this:
var Rabbit = new Function('console.log("shiv")');
Now, you might guess it out. If you add a new property to a Function object, as long as you don't overwrite the existing one, the function is still working just fine.
do this add a variable bark to function
- No, the function has it own closure, the only way to add variable to the function is to bind it to
this
object using Rabbit.bind(object)
do this added a property to Rabbit object
- Well, since the "Rabbit object" is just an object, Yes.
这篇关于javascript将属性添加到函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!