不确定函数的实例

时间:2013-06-18 09:01:51

标签: javascript

<script>
var myObject = function(name){
    this.name = name;
    return this;
};

myObject.prototype.getName = function(){
    return this.name;
};
console.log(myObject instanceof Function); // true
</script>

问题:

如何理解这一行:console.log(myObject instanceof Function); // true?如果我们想要制作实例,我们需要使用new关键字,对吧?类似于:var myObject = new Function();,那么myObject如何成为Function的实例?

2 个答案:

答案 0 :(得分:1)

myObject是一个函数,每个函数都是Function的实例。

console.log(myObject instanceof Function); // true
console.log(new myObject('foo') instanceof myObject); // true

答案 1 :(得分:0)

  

如果我们想要创建实例,我们需要使用new关键字,对吗?

一般。函数表达式也会返回函数对象。