简体   繁体   English

javascript中函数和对象的本质区别是什么?

[英]What's substantive difference between function and Object in javascript?

When I learn js at first I get a voice which say everything is an object, so I think maybe function is an object and object is an object too.当我刚开始学习 js 时,我听到一个声音说一切都是对象,所以我想也许函数是一个对象,对象也是一个对象。

But when I learn prototype, some thing different to my thought.但是当我学习原型时,有些事情与我的想法不同。

function helloworld(){                                                                       
    this.hi = 'world';
}
var foo = { 
    'sth':'happend'
};


function bar(){};

bar.prototype = foo;
console.log(new bar().sth);

bar.prototype = helloworld;
console.log(new bar().hi);

And I get print我得到打印

happend
undefined

Then I replace bar.prototype = helloworld;然后我替换bar.prototype = helloworld; to bar.prototype = new helloworld(); to bar.prototype = new helloworld(); I get correct result.我得到正确的结果。

happend
world

I'm a newbie, maybe it's a stupid question, but I really want to know what's wrong in my mind?我是新手,也许这是一个愚蠢的问题,但我真的很想知道我的想法是什么? is function not an Object?函数不是对象吗? could anybody help me?有人可以帮我吗? thanks a lot..多谢..

Yes, a function is an object, and can have properties as well:是的,函数是一个对象,也可以有属性:

var foo = {};
var bar = function(x){return x+1};
foo.prop = "hello ";
bar.prop = "world!"; // works the same!
alert(foo.prop + bar.prop);

What's substantive difference between function and Object?函数和对象之间有什么实质性区别?

Well, a function is an object that can be called - "normal" objects can't:好吧,函数是一个可以被调用的对象——“普通”对象不能:

bar(4); // 5
foo(4); // Error: 'foo' is not a function

I replace bar.prototype = helloworld;我替换bar.prototype = helloworld; with bar.prototype = new helloworld();使用bar.prototype = new helloworld(); to get correct result得到正确的结果

I really want to know what's wrong in my mind?我真的很想知道我的脑子里出了什么问题?

You must not confuse constructor functions for instances that were created by calling them.对于通过调用创建的实例,您不能混淆构造函数。 helloworld is an object (just as bar is in the example above), but it's a very different object than new helloworld() (which inherits from helloworld.prototype , and was initialised by the constructor with a hi property). helloworld是一个对象(就像上面例子中的bar ),但它与new helloworld()是一个非常不同的对象(它继承自helloworld.prototype ,并由具有hi属性的构造函数初始化)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM