In javascript, what is a constructor? And what isn't?

心已入冬 提交于 2019-12-11 00:24:47

问题


I'm using a plugin for jQuery. It works great in webkit, but when I try it in firefox I get the following firefox error:

google.maps.Geocoder is not a constructor
$('.to, .from').geo_autocomplete(new google.maps.Geocoder, { 

Here is all the jquery:

$('.to, .from').geo_autocomplete(new google.maps.Geocoder, {
mapkey: 'ABQIAAAAbnvDoAoYOSW2iqoXiGTpYBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQNumU68AwGqjbSNF9YO8NokKst8w', 
selectFirst: false,
minChars: 3,
cacheLength: 50,
width: 235,
scroll: true,
scrollHeight: 330
});

What's a constructor and howcome firefox is pointing it out to me?

http://dev.resihop.nu is the site


回答1:


Any native function may be called as a constructor (even if it wasn't designed to be). Anything that's not callable also cannot be a constructor. eg new 3 gives the same error.

In your page, google.maps.Geocoder is simply undefined, which certainly isn't going to help. Looking at Google's maps script it's failing to load the Geocoder module because it's using document.write to do so, a method that has to be run from a <script> included in the HTML document at parse time, not imported by use of DOM scripting as you're doing here.

It certainly doesn't expect to be run from a page loaded via client-side XSLT. This is going to give you lots of browser problems and zero SEO presence. What is the purpose of this craziness?




回答2:


A constructor is the function (which returns an object of the function name's type) that is invoked when you use new in conjunction with that function's name, such as:

function Person(name, age) {
   //blah
}

var me = new Person("Jacob", 20);



回答3:


You msut use google.maps.geocoder like this:

$('.to, .from').geo_autocomplete(new google.maps.Geocoder({
  mapkey:'ABQIAAAAbnvDoAoYOSW2iqoXiGTpYBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQNumU68AwGqjbSNF9YO8NokKst8w', 
  selectFirst: false,
  minChars: 3,
  cacheLength: 50,
  width: 235,
  scroll: true,
  scrollHeight: 330
}));



回答4:


When you instantiate an object, e.g. create an instance of an object, the constructor is the first method that is called within your object.

When you're calling

new google.maps.Geocoder

...you are attempting instantiate a parameterless constructor of the object by using the new keyword. In this case, Geocoder is not a class that can be instantiated without parameters, or at all.



来源:https://stackoverflow.com/questions/4044259/in-javascript-what-is-a-constructor-and-what-isnt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!