function对象都是Function的实例:
> Object.getOwnPropertyNames(Function)
[ 'length',
'name',
'arguments',
'caller',
'prototype' ]
所以function对象也应该有这些方法或者是属性:
<script type="text/javascript">
var myFunction = function func(name,age){
//请注意,直接调用这个函数的时候this指向谁
console.log(myFunction);
console.log(myFunction.length);
console.log(myFunction.name);
console.log(myFunction.arguments);
console.log(myFunction.caller);
console.log(myFunction.prototype);
}
myFunction.print = function(){
//调用这个myFunction对象的时候this指向的是myFunction这个函数对象,这个你必须搞明白
console.log(this);
console.log(this.length);
console.log(this.name);
console.log(this.arguments);
console.log(this.caller);
console.log(this.prototype);
}
myFunction.prototype.print_name = function(){
console.log('print_name');
}
myFunction('name',22);
myFunction.print();
</script>
所以如果你想要拓展函数,可以给函数添加一些方法:
var myFunction = function func(name,age){}
myFunction.print = function(){
console.log("name");
}
myFunction.print();
如果你想要让所有的函数都有某些属性,那就必须修改Function.prototype了
var myFunction = function func(name,age){}
Function.prototype.print = function(){
console.log("name");
}
myFunction.print();
把函数对象也当成对象,感觉特别不习惯,因为习惯上我会这样做(你让我想象一下,在java中类里面的方法也是对象,可以被调用,然后这个方法还可以有自己的属性,这是多么不可想象的):
var myFunction = function func(name,age){
this.name = name;
this.age = age;
}
我以为我的真的给这个函数对象添加了name和age属性,但是实际上你要这样做:
var myFunction = function func(){
}
myFunction.name = 'myFunction';
myFunction.age = 19;
console.log(myFunction.name);
console.log(myFunction.age);
这时候你就会发现它跟你创建的其他普通对象是不一样的,比如:
var MyObject = function func(){
this.name = 'name';
this.age = 20
}
var my = new MyObject()
console.log(my.age);
你会想怎么这种对象会这么奇特,不是跟function对象添加属性是一样的
Function.method('new', function ( ) {
// Create a new object that inherits from the
// constructor's prototype.
var that = Object.create(this.prototype);
// Invoke the constructor, binding –this- to
// the new object.
var other = this.apply(that, arguments);
// If its return value isn't an object,
// substitute the new object.
return (typeof other === 'object' && other) || that;
});
原因就是new这个操作符所做的操作跟上面这个函数是一样的
所以现在function对象跟其他的object对象就应该统一在一起了:
var myFunction = function func(){
}
myFunction.name = 'name';
myFunction.age = 29
myFunction.get_age = function(){
console.log(this.age);
}
myFunction.get_age();
函数还有一个特点就是他是可以被调用的,它被调用的时候this是根据上下文指向不同的对象