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

时间:2015-06-25 10:04:38

标签: 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.

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; 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..

1 个答案:

答案 0 :(得分:1)

是的,函数是一个对象,也可以有属性:

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

功能和对象之间有什么实质性区别?

好吧,函数是一个可以调用的对象 - “普通”对象不能:

bar.prototype = helloworld;
  

我将bar.prototype = new helloworld();替换为helloworld以获得正确的结果

     

我真的想知道我的想法是什么?

您不能将构造函数与通过调用它们创建的实例混淆。 bar是一个对象(就像上面示例中的new helloworld()一样),但它是一个与helloworld.prototype非常不同的对象(它继承自hi,并且由redditFile = urllib2.urlopen("http://www.bing.com/videos?q="+urllib.quote_plus(word)) redditHtml = redditFile.read() redditFile.close() soup = BeautifulSoup(redditHtml) productDivs = soup.findAll('div', attrs={'class' : 'dg_u'}) for div in productDivs: print div.find('a')['vrhm'] #This element contains youtube urls but print does not display it if div.find('div', {"class":"vthumb", 'smturl': True}) is not None: print div.find('div', {"class":"vthumb", 'smturl': True})['smturl'] #this gives link to micro video 初始化具有a属性的构造函数。)