「this.init is not a function」エラーの原因と解決方法

このQ&Aのポイント
  • 上記のスクリプトで、「this.init is not a function」というエラーが出る原因は、thisの参照先が予想と異なるためです。
  • このエラーは、thisがイベントハンドラ内で正しくバインドされていない場合に発生します。
  • 解決するためには、コード内でthisの参照を明示的に指定する必要があります。bindメソッドを使用して、thisを明示的に指定することでエラーを解消できます。
回答を見る
  • ベストアンサー

is not a functionというエラー

jqueryのスクリプトを書いていたところ $(function () { var wrapper = $("#main"); var wrapperWidth; var blocks = []; NewBlocks(blocks, wrapper.children()); function NewBlocks(blocks, elements) { for (var i = 0; i < elements.length; i++) { var element = elements[i]; var block = new Block(element); blocks.push(block) } } function Block(element) { this.element = element; element.style.margin = "10px"; this.init(); } Block.prototype = { init: function () { this.width = this.element.offsetWidth; this.height = this.element.offsetHeight; } } }); 上記スクリプトを実行すると「this.init is not a function」というエラーが出てしまいます。 一体何をどう間違っているせいでエラーが出るのか、どうかご教授いただけますでしょうか。

質問者が選んだベストアンサー

  • ベストアンサー
  • askaaska
  • ベストアンサー率35% (1455/4149)
回答No.1

理由は今まで悩んでいたのがむなしくなるほどシンプルなものよ   利用する前に宣言すること これだけ NewBlocks(blocks, wrapper.children()); より前に Block.prototype を書いてあげればいいわ

otyanoco
質問者

お礼

ご指摘の通りに書き換えた所、問題なく動きました。 参考にしたスクリプトや、書籍では後ろに書いて動いていたのですが……、何が違うのやら。 ご回答いただき、ありがとうございました。

関連するQ&A

  • prototype.js で $ is not defined になってしまう!

    JSバージョン:prototype1.6 ブラウザ:Firefox2.0、IE7.0 OS:WinXPpro でシンプルに <html> <head> <title>$ - 指定idのエレメントを取得</title> </head> <script type="text/javascript" src="/js/prototype.js?aaads"></script> <script type="text/javascript"> function test1() { var element = $('div1'); alert(element.innerHTML); } </script> <body> <div id="div1">DIV1の中身</div> </body> </html> を実行したところ、$ is not defined と エラーになってしまいます。 あるレンタルサーバにUPして動かすと問題なく、 ローカルPCで実行するとエラーになってしまうようです。 どなたか教えて下さい!!!

  • 個別では動く、javascriptのエラー

    こちらで良いのか悩みましたが..... blogやHPを作った事があるというだけで、webshopの作りを友人にお願いされた初心者です。 更新履歴用にFeed2JS、商品画像を表示する為にmootools、lightbox2をお借りして 設置までは何とか行う事が出来、個別ではちゃんと動いているのですが、同じページではどちらかが動かなくなってしまいました。 ブラウザにエラーコンソールを付けてみた所、mootoolsとrssにエラーがあると表示されていて、 どの行がエラーなのかは分かりましたが、情けない話ですが何がエラーなのかが分かりません。 javascriptは見よう見まねで設置しており、コードの書き換えなどは画像サイズを変更するぐらいがやっとです。 ネットや辞書で調べてみましたが、分からないまま弄ると余計におかしな事になり、怖くなってきました。 周りに詳しい人もおらず、困ってしまいましたので、検索でみつけたこちらでお伺いする事にした次第です。 エラー表示されるのは $(document).ready( function(){ $('.rss-items').innerfade({ animationtype: 'slide', speed: 750, timeout: 6000, type: 'sequence', containerheight: '1em' }); $('ul#portfolio').innerfade({ speed: 1000, timeout: 5000, type: 'sequence', containerheight: '220px' }); $('.fade').innerfade({ speed: 1000, timeout: 6000, type: 'random_start', containerheight: '1.5em' }); $('.adi').innerfade({ speed: 'slow', timeout: 5000, type: 'random', containerheight: '150px' }); }); の3行目 $('.rss-items').innerfade({ 長いので直接アドレスを貼ります http://pretto.kilo.jp/cos-pretto/js/mootools-1.2-core.js 345行目 Fx.Slide=new Class({Extends:Fx,options:{mode:'vertical'},initialize:function(a,b){this.addEvent('complete',function(){this.open=(this.wrapper['offset'+this.layout.capitalize()]!=0);if(this.open&&Browser.Engine.webkit419)this.element.dispose().inject(this.wrapper)},true);this.element=this.subject=$(a);this.parent(b);var c=this.element.retrieve('wrapper');this.wrapper=c||new Element('div',{styles:$extend(this.element.getStyles('margin','position'),{'overflow':'hidden'})}).wraps(this.element);this.element.store('wrapper',this.wrapper).setStyle('margin',0);this.now=[];this.open=true},vertical:function(){this.margin='margin-top';this.layout='height';this.offset=this.element.offsetHeight},horizontal:function(){this.margin='margin-left';this.layout='width';this.offset=this.element.offsetWidth},set:function(a){this.element.setStyle(this.margin,a[0]);this.wrapper.setStyle(this.layout,a[1]);return this},compute:function(a,b,c){var d=[];var x=2;x.times(function(i){d[i]=Fx.compute(a[i],b[i],c)});return d},start:function(a,b){if(!this.check(arguments.callee,a,b))return this;this[b||this.options.mode]();var c=this.element.getStyle(this.margin).toInt();var d=this.wrapper.getStyle(this.layout).toInt();var e=[[c,d],[0,this.offset]];var f=[[c,d],[-this.offset,0]];var g;switch(a){case'in':g=e;break;case'out':g=f;break;case'toggle':g=(this.wrapper['offset'+this.layout.capitalize()]==0)?e:f}return this.parent(g[0],g[1])},slideIn:function(a){return this.start('in',a)},slideOut:function(a){return this.start('out',a)},hide:function(a){this[a||this.options.mode]();this.open=false;return this.set([-this.offset,0])},show:function(a){this[a||this.options.mode]();this.open=true;return this.set([0,this.offset])},toggle:function(a){return this.start('toggle',a)}}); です。 マヌケな質問かもしれませんが、参考になるページだけでも教えて頂けると凄く嬉しいです。

  • javascriptについて

    現在HPを作成していてjavaのプルダウンメニューを設置していますが 最初からメニューが開いた状態になります。ちなみにsdmenu.jsを使用しています。 最初開いた時にメニューが閉じるようにできますでしょうか? function SDMenu(id) { if (!document.getElementById || !document.getElementsByTagName) return false; this.menu = document.getElementById(id); this.submenus = this.menu.getElementsByTagName("div"); this.remember = true; this.speed = 4; this.markCurrent = true; this.oneSmOnly = false; } SDMenu.prototype.init = function() { var mainInstance = this; for (var i = 0; i < this.submenus.length; i++) this.submenus[i].getElementsByTagName("span")[0].onclick = function() { mainInstance.toggleMenu(this.parentNode); }; if (this.markCurrent) { var links = this.menu.getElementsByTagName("a"); for (var i = 0; i < links.length; i++) if (links[i].href == document.location.href) { links[i].className = "current"; break; } } if (this.remember) { var regex = new RegExp("sdmenu_" + encodeURIComponent(this.menu.id) + "=([01]+)"); var match = regex.exec(document.cookie); if (match) { var states = match[1].split(""); for (var i = 0; i < states.length; i++) this.submenus[i].className = (states[i] == 0 ? "collapsed" : ""); } } }; SDMenu.prototype.toggleMenu = function(submenu) { if (submenu.className == "collapsed") this.expandMenu(submenu); else this.collapseMenu(submenu); }; SDMenu.prototype.expandMenu = function(submenu) { var fullHeight = submenu.getElementsByTagName("span")[0].offsetHeight; var links = submenu.getElementsByTagName("a"); for (var i = 0; i < links.length; i++) fullHeight += links[i].offsetHeight; var moveBy = Math.round(this.speed * links.length); var mainInstance = this; var intId = setInterval(function() { var curHeight = submenu.offsetHeight; var newHeight = curHeight + moveBy; if (newHeight < fullHeight) submenu.style.height = newHeight + "px"; else { clearInterval(intId); submenu.style.height = ""; submenu.className = ""; mainInstance.memorize(); } }, 30); this.collapseOthers(submenu); }; SDMenu.prototype.collapseMenu = function(submenu) { var minHeight = submenu.getElementsByTagName("span")[0].offsetHeight; var moveBy = Math.round(this.speed * submenu.getElementsByTagName("a").length); var mainInstance = this; var intId = setInterval(function() { var curHeight = submenu.offsetHeight; var newHeight = curHeight - moveBy; if (newHeight > minHeight) submenu.style.height = newHeight + "px"; else { clearInterval(intId); submenu.style.height = ""; submenu.className = "collapsed"; mainInstance.memorize(); } }, 30); }; SDMenu.prototype.collapseOthers = function(submenu) { if (this.oneSmOnly) { for (var i = 0; i < this.submenus.length; i++) if (this.submenus[i] != submenu && this.submenus[i].className != "collapsed") this.collapseMenu(this.submenus[i]); } }; SDMenu.prototype.expandAll = function() { var oldOneSmOnly = this.oneSmOnly; this.oneSmOnly = false; for (var i = 0; i < this.submenus.length; i++) if (this.submenus[i].className == "collapsed") this.expandMenu(this.submenus[i]); this.oneSmOnly = oldOneSmOnly; }; SDMenu.prototype.collapseAll = function() { for (var i = 0; i < this.submenus.length; i++) if (this.submenus[i].className != "collapsed") this.collapseMenu(this.submenus[i]); }; SDMenu.prototype.memorize = function() { if (this.remember) { var states = new Array(); for (var i = 0; i < this.submenus.length; i++) states.push(this.submenus[i].className == "collapsed" ? 0 : 1); var d = new Date(); d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000)); } };

  • JavaScriptエラーが出ます…

    2つのJavaScriptエラーが出て大変困っております。 どなたか分かる方いらっしゃいませんでしょうか? ※当方はJavaScriptは分かりません。 検索にて調査いたしましたが、情けないですがもうお手上げ状態です。 ▼1つめ----------------------------------------------▼ メッセージ: 'null' は Null またはオブジェクトではありません。 ライン: 8 文字: 3 コード: 0 コード内容 以下 var accordion=function(){ var tm=10; var sp=10; function slider(n){ this.nm=n; this.arr=[]; this.sel='' } slider.prototype.init=function(t,c,k){ var a,h,s,l,i; a=document.getElementById(t); h=a.getElementsByTagName('dt'); s=a.getElementsByTagName('dd'); l=h.length; for(i=0;i<l;i++){ var d=h[i]; this.arr[i]=d; d.onclick=new Function(this.nm+".process(this)"); if(k!=null&&c==i){this.sel=d.className=k} } l=s.length; for(i=0;i<l;i++){ var d=s[i]; d.maxh=d.offsetHeight; if(c!=i){d.style.height='0'; d.style.display='none'} } } slider.prototype.process=function(d){ var i,l; l=this.arr.length; for(i=0;i<l;i++){ var h=this.arr[i]; var s=h.nextSibling; if(s.nodeType!=1){s=s.nextSibling} clearInterval(s.timer); if(h==d&&s.style.display=='none'){ s.style.display=''; setup(s,1); h.className=this.sel} else if(s.style.display==''){setup(s,-1); h.className=''} } } function setup(c,f){c.timer=setInterval(function(){slide(c,f)},tm)} function slide(c,f){ var h,m,d; h=c.offsetHeight; m=c.maxh; d=(f==1)?Math.ceil((m-h)/sp):Math.ceil(h/sp); c.style.height=h+(d*f)+'px'; c.style.opacity=h/m; c.style.filter='alpha(opacity='+h*100/m+')'; if(f==1&&h>=m){clearInterval(c.timer)} else if(f!=1&&h==1){c.style.display='none'; clearInterval(c.timer)} } return{slider:slider} }(); ▲1つめここまで----------------------------------------------▲ ▼2つめ----------------------------------------------▼ メッセージ: 'obj.length' は Null またはオブジェクトではありません。 ライン: 238 文字: 10 コード: 0 コード内容 以下 http://www.myulond.com/js.txt ▲1つめここまで----------------------------------------------▲ どうぞ、ご教授よろしくお願いいたします。

  • Java script エラー

    以前、質問して教えていただいたJava scriptですが、 サーバにアップしたところ Java script エラー 「pages[i].style.display = 'none';」が発生しました。 Java scriptの知識が全くない素人で申し訳ないのですが、 エラーの原因を教えていただけますでしょうか? よろしくお願いいたします。 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "​http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">​ <html xmlns="​http://www.w3.org/1999/xhtml"​ xml:lang="ja" lang="ja"> <head> <title>タブ切替のサンプル</title> <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS" /> <script type="text/javascript"> // <![CDATA[ var tab = { peek:0, init: function(start){ var tabs = this.setup.tabs; var pages = this.setup.pages; for(var i=0; i<pages.length; i++) { if(i !== 0) pages[i].style.display = 'none'; tabs[i].onclick = function(){ tab.showpage(this); return false; }; } this.peek = start; this.showpage(tabs[this.peek]); }, showpage: function(obj){ var tabs = this.setup.tabs; var pages = this.setup.pages; var num; for(num=0; num<tabs.length; num++) { if(tabs[num] === obj) { tab.peek = num; break; } } for(var i=0; i<pages.length; i++) { if(i == num) { pages[num].style.display = 'block'; tabs[num].className = 'present'; } else{ pages[i].style.display = 'none'; tabs[i].className = null; } } } } function initialize(){ tab.setup = { tabs: document.getElementById('tab').getElementsByTagName('li'), pages: [ document.getElementById('page1'), document.getElementById('page2'), document.getElementById('page3'), document.getElementById('page4'), document.getElementById('page5') ] } tab.init(0); } function proceed(num){ if(tab.peek + num < tab.setup.tabs.length && 0 <= tab.peek + num){ tab.showpage(tab.setup.tabs[tab.peek + num]); } } // ]]> </script>

  • Javascriptリアルタイムエラーチェック

    Javascript初心者です。 本を見ながらフォームの入力値のリアルタイムエラーチェックを実装しています。 テキストフィールドへの入力値の妥当性検証はできるのですが、 チェックボックスが一つもチェックされていなかった場合にチェックボックスを囲むfieldsetを赤くさせるのがうまくいきません。 電話番号の形式指定ならば String.prototype.isZip = function(){ return this.isEmpty()||/^\d{3}-\d{4}$/.test(this); } という形です。thisはname属性を参照します。 すべての項目にエラーがない場合に確認画面へ進めるようにしています。 String.prototype.isNotEmpty = function() { return this != ''; } String.prototype.isEmpty = function(){ return this == ''; } String.prototype.isShorterThan = function(n){ return this.length<=n; } String.prototype.isLongerThan = function(n){ return this.length >= n; } String.prototype.isZip = function(){ return this.isEmpty()||/^\d{3}-\d{4}$/.test(this); } String.prototype.isPhone = function() { return this.isEmpty()||/^\d{2,4}-\d{1,4}-\d{4}$/. test(this); } String.prototype.isEmail = function() { return this.isEmpty()||/^([\w-]+\.?)+@[\w-]+(\.([\w-]+))+$/.test(this); } var formValidation = function(name, feedback, fields){ var form = document.forms[name]; for (var i=0; i<form.elements.length; i++){ (function(){ var elm = form.elements[i]; var f = fields[elm.name]; if (f){ f.element = elm; f.process = function(){ var ok = true; if (f.convert) f.element.value = f.convert(f.element.value); if (f.validation) ok = f.validation(f.element.value); if (f.feedback) f.feedback(ok, f.element); return ok; } elm.onblur = function(e){ f.process() } } })(); } form.onsubmit = function(){ var all_ok = true; for (key in fields) if (fields[key] && !fields[key].process()) all_ok = false; return feedback(all_ok); }; } </script> <script type="text/javascript"> <!-- <![CDATA[ window.onload = function(){ var fields = { 'last_name':{ convert: function(val){ return val.cnvKana('asKV').trim() }, validation: function(val){ return val.isNotEmpty() && val.isShorterThan(16) }, feedback: function(ok, elm){elm.style.border = ok ? 'solid 2px #3CB371' : 'solid 2px f57272'; } }, 'furigana':{ convert: function(val){ return val.cnvKana('sKVC').trim() }, validation: function(val){ return val.isNotEmpty() && val.isComposedOf(cs.kata.zen+cs.space.han) && val.isShorterThan(32) }, feedback: function(ok, elm){ elm.style.border = ok ? 'solid 2px #3CB371' : 'solid 2px f57272'; } }, 'phone':{ convert: function(val){ return val.cnvPhone() }, validation: function(val){ return val.isNotEmpty() && val.isPhone() }, feedback: function(ok, elm){elm.style.border = ok ? 'solid 2px #3CB371' : 'solid 2px f57272';} } 'email':{ convert: function(val){ return val.trim() }, validation: function(val){ return val.isNotEmpty() && val.isEmail() }, feedback: function(ok, elm){ elm.style.border = ok ? 'solid 2px #3CB371' : 'solid 2px f57272';}, }, }; var feedback = function(ok){ if (ok) alert("確認画面へ進みます。"); else alert("フォームの内容に不備があるようです。再度の確認をお願いいたします。") return ok; }; new formValidation('MAINFORM', feedback, fields); } // ]]> --> <form name="MAINFORM" action="check.php" method="post"> <input name="last_name" type="text"> <input name="furigana" type="text" /> ~~~~~~ <fieldset id="checkboxDemo" name="job"> <legend><img src="images/label_kozanaiyou.gif" width="92" height="18"></legend> <label for="checkbox-1" tabindex="1">オフィス(Word,Excel)</label> <input type="checkbox" name="kouza[]" id="checkbox-1" value="オフィス(Word,Excel)" /> <label for="checkbox-2" tabindex="2">ネットワーク構築</label> <input type="checkbox" name="kouza[]" id="checkbox-2" value="ネットワーク構築" /> <label for="checkbox-3" tabindex="3">WEBデザイン</label><input type="checkbox" name="kouza[]" id="checkbox-3" value="WEBデザイン" /> <label for="checkbox-4" tabindex="4">WEBプログラミング</label> <input type="checkbox" name="kouza[]" id="checkbox-4" value="WEBプログラミング" />  </fieldset> 自分で色々と試してみましたがうまくいかず、皆様のお力を借りたいと思い投稿しました。 詳しい方教えてください。

  • javascriptのconstructorプロパティについて

    constructorプロパティとは、 オブジェクトの初期化で使用されたコンストラクタ関数を参照 とのことなので、下記2パターンのPGを作成しました 1.prototypeの明記なし function Hoge(){ this.init = "Hogeで初期化"; this.getInit = function(){ return this.init; } } var obj = new Hoge(); alert(obj.constructor == Hoge); for(prop in obj){ alert( prop + " - " + obj[prop]); } //実行結果 True init - Hogeで初期化 getInit - function () { return this.init; } 2.prototypeの明記あり function Hoge(){ this.initialize.apply(this,arguments); this.init = "Hogeで初期化"; this.getInit = function(){ return this.init; } } Hoge.prototype ={ initialize:function(){ this.init = "Hoge.prototype.initializeで初期化"; }, getInit:function(){ return "Hoge.prototype.getInit()"; } } var obj = new Hoge(); alert(obj.constructor == Hoge); for(prop in obj){ alert( prop + " - " + obj[prop]); } //実行結果 false init - Hogeで初期化 getInit - function () { return this.init; } initialize - function () { this.init = "Hoge.prototype.initialize\u3067\u521D\u671F\u5316"; } ・質問内容 prototypeの明記なしの場合は、Hogeのコンストラ関数を参照している(結果がTrueのため) prototypeの明記ありの場合は、falseのためコンストラ関数を参照していないのですが、 prototype明記あり、なしで結果が異なる理由が分からない状態です。 (prototype.constructorにも手を出したのですが、上記が解決しないため  constructorプロパティに関してのみ質問した次第です) ネット、書籍等で調べたのですが、検討がつかない状態です。 お手数ですが、ご教授お願い致します。

  • 配列に代入したエレメントを操作できない(変数のスコープの問題でしょうか?)

    ページ上に複数のブロックを配置しています。ひとつにマウスオーバーすると枠の色が赤くなり、他のものの枠の色がグレーになるようにします。 以下にソースを記します。 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=euc-jp"> <title>array</title> <style type="text/css"> div { width: 50%; margin: 5px; padding: 5px; border: 3px solid #bbb; } </style> <script type="text/javascript"> <!-- var blockArr = new Array(); blockArr.push('First'); blockArr.push('Second'); blockArr.push('Third'); blockArr.push('Fourth'); blockArr.push('Fifth'); var blocks = new Array(); function init() { for (var i=0; i<blockArr.length; i++) { var theName = blockArr[i]; blocks[i] = document.getElementById('block' + theName); blocks[i].onmouseover = function() { for (var ii=0; ii<blockArr.length; ii++) { if (i==ii) { // nothing } else { blocks[ii].style.border = '3px solid #bbb'; } } blocks[i].style.border = '3px solid red'; // ←←← 変更箇所 }; } } window.onload = init; //--> </script> </head> <body> <div id="blockFirst">1</div> <div id="blockSecond">2</div> <div id="blockThird">3</div> <div id="blockFourth">4</div> <div id="blockFifth">5</div> </body> </html> FireFox2で表示したところ、これでは blocks[i] has no properties というエラーが出て動作しません。 試しに『// ←←← 変更箇所 』の行の宣言を『this.style.border = '3px solid red';』と this に変えてみたら動作しました。 しかしなぜ blocks[i] で動作しないのでしょうか。

  • 効率良くイベントに引数を渡すやり方

    sample2に引数「x」「y」を渡したいが為に 次のように何段階も同じような作業をしなくてはならない方法しか 自分は思いつかないのですが、何かもっと効率的な方法はあるのでしょうか? function main() { var element = document.createElement('div'); element.x = x; element.y = y; element.onclick = function(){ sample1(this.x, this.y); }; } function sample1(x, y) { var element = document.createElement('span'); element.x = x; element.y = y; element.onclick = function(){ sample2(this.x, this.y); }; } function sample2(x, y) { alert("x="x+" y="+y); }

  • アコーディオンのフォントがIEのみ適用にならない

    以下のソースなのですが、Firefox/Operaはスタイルシート指定のメイリオ表示なのですが、 IE8で閲覧すると文字がぼやけて表示されます。どこに原因があるでしょうか? よろしくお願いいたします --- var accordion=function(){ var tm=sp=10; function slider(n){this.nm=n; this.arr=[]} slider.prototype.init=function(t,c,k){ var a,h,s,l,i; a=document.getElementById(t); this.sl=k?k:''; h=a.getElementsByTagName('dt'); s=a.getElementsByTagName('dd'); this.l=h.length; for(i=0;i<this.l;i++){var d=h[i]; this.arr[i]=d; d.onclick=new Function(this.nm+'.pro(this)'); if(c==i){d.className=this.sl}} l=s.length; for(i=0;i<l;i++){var d=s[i]; d.mh=d.offsetHeight; if(c!=i){d.style.height=0; d.style.display='none'}} } slider.prototype.pro=function(d){ for(var i=0;i<this.l;i++){ var h=this.arr[i], s=h.nextSibling; s=s.nodeType!=1?s.nextSibling:s; clearInterval(s.tm); if(h==d&&s.style.display=='none'){s.style.display=''; su(s,1); h.className=this.sl} else if(s.style.display==''){su(s,-1); h.className=''} } } function su(c,f){c.tm=setInterval(function(){sl(c,f)},tm)} function sl(c,f){ var h=c.offsetHeight, m=c.mh, d=f==1?m-h:h; c.style.height=h+(Math.ceil(d/sp)*f)+'px'; c.style.opacity=h/m; c.style.filter='alpha(opacity='+h*100/m+')'; if(f==1&&h>=m){clearInterval(c.tm)}else if(f!=1&&h==1){c.style.display='none'; clearInterval(c.tm)} } return{slider:slider} }(); var slider1=new accordion.slider("slider1"); slider1.init("slider"); var slider2=new accordion.slider("slider2"); slider2.init("slider2",0,"open"); var slider3=new accordion.slider("slider3"); slider3.init("slider3",0,"open");