console.trace('trace car')



Get the stack trace for a function

If you’re using a javascript framework you know that it quickly produces a lot of code. Views are created, events are triggering functions and in the end you want to know what caused this function call. Since Javascript is not a very structured language it can sometimes be hard to get an overview of what happened and when. Especially when you jump into someone else’s code. This is when console.trace (or just trace in the console) comes handy.

Imagine you want to see the entire stack trace for the function call funcZ in the car instance on line 33:

Line 33 will output…

Console trace
Console trace

Now we can clearly see that function func1 called func2 which called func4. Func4 created an instance of Car and then called the function car.funcX and so on.

Even though you think you know your script well this can still be quite handy. Let’s say you want to improve your code. Get the trace and your great list of all related functions. Every single one is clickable and you can now go back and fourth between these functions. It’s like a menu of functions just for you.

Posted by 이상욱1
,


Useful Javascript debugging tips you didn’t know

The Raygun team is made up of a bunch of nerdy folk just like yourself. Occasionally they write about tools they like and thoughts they have about dev-type topics. This week we’ve got Rick, our longboarding-freediving-Swedish speaking front-end dev talking about ‘things you didn’t know about Javascript debugging’.

Knowing your tools can make a major difference when it comes to getting things done. This is a list of small debugging tips you probably didn’t know but soon won’t live without. In this post, most of the tips are for Chrome inspector even though my favourite tips are for Firefox. Many of these tips will work in other inspectors as well.

Quick find your DOM elements.

Mark a dom element in the elements panel and use it in your console. Chrome inspector keeps the last 5 elements in its history, so the last marked element will be displayed with $0, second to last marked element $1 and so on.

If you mark following items in order’item-4′, ‘item-3′, ‘item-2′, ‘item-1′, ‘item-0′ then you can access the DOM nodes like this in the console.

Debug javascript

Display object as tables

Sometimes it can be a bit messy to view a lot of data with console.log. You can display a list of objects as a table to view complex sets of data more easily.

Will output…

console.table
console.table

Get the stack trace for a function

If you’re using a javascript framework you know that it quickly produces a lot of code. Views are created, events are triggering functions and in the end you want to know what caused this function call. Since Javascript is not a very structured language it can sometimes be hard to get an overview of what happened and when. Especially when you jump into someone else’s code. This is when console.trace (or just trace in the console) comes handy.

Imagine you want to see the entire stack trace for the function call funcZ in the car instance on line 33:

Line 33 will output…

Console trace
Console trace

Now we can clearly see that function func1 called func2 which called func4. Func4 created an instance of Car and then called the function car.funcX and so on.

Even though you think you know your script well this can still be quite handy. Let’s say you want to improve your code. Get the trace and your great list of all related functions. Every single one is clickable and you can now go back and fourth between these functions. It’s like a menu of functions just for you.

Quick find a function to debug

Let’s say you want to set a breakpoint in a function. The two most common ways to do that is probably to find the line in your inspector and add a breakpoint. Another way would be to add a debugger in your script. In both of these solutions, you have to click around in your files to find the particular line you want to debug.

What is probably less common is to use the console. Use debug(funcName) in the console and the script will stop when it reaches the function you passed in. It’s quick but the downside is it doesn’t work on private or anonymous functions. But if that’s not the case it’s probably the fastest way to find a function to debug. Note that there’s a function called console.debug which is not the same thing.

Type debug(car.funcY) in the console and the script will stop in debug mode when it gets a function call to car.funcY.

debug(car.funcY)
debug(car.funcY)

Black box scripts that are NOT relevant

Today we often have a few libraries and frameworks on our web apps. Most of them are well tested and relatively bug free. But we still debug our own scripts and the debugger still steps in to all those files that have no relevance for this debugging task. The solution is to black box the script you don’t need to debug. This could also include your own scripts. Read more about black boxing in my previous article javascript-debugging-with-black-box.

Find the important things in complex debugging

In more complex debugging we sometimes want to output many lines. One thing you can do to keep a better structure of your outputs is to use more console functions like: Console.log, console.debug, console.warn, console.info, console.error and so on. You can then filter them in your inspector. But sometimes this is not really what you want. It’s now that YOU can get creative and style your messages. Use CSS and make your own structured console messages.

will output…

Custom console message
Custom console message

In the console.log() you can for example set %s for a string%i for integers and %c for custom style. You can probably find better ways to use this. If you use a single page framework you maybe want to have one style for view message and another for models, collections, controllers and so on. Maybe also name the shorter like wlog, clog and mlog. It’s time to use your own imagination.

Watch specific function calls and it’s arguments

In the chrome console you can keep an eye on specific functions. Every time the function is called it will be logged with the values that was passed in.

Monitor
Monitor

This is a great way to see what arguments are passed into a function. But I must say it would be good if the console could tell how many arguments were expected. In the above example func1 expect 3 arguments but only 2 is passed in. If that’s not handled in the code it could lead to a possible bug.

Quickly access elements in the console

A faster way to do a querySelector in the console is with the dollar sign. $(‘css-selector’) will return the first match of CSS selector. $$(‘css-selector’) will return all of them. If you are using an element more than once it is worth it to save it as a variable.

debug javascript

Post man is great but Firefox is faster

Many developers are using Postman to play around with ajax requests. Postman is great but I must say it’s a bit annoying to open up a new browser window, write new request objects and then test them. Sometimes it’s easier to use your browser.  When you do so you no longer need to worry about authentication cookies if you are sending to a password secure page. This is how you would edit and resend requests in firefox.

Open up the inspector and go to the network tab. Right click on the desired request and choose Edit and Resend. Now you can change anything you want. Change the header and edit your parameters and the simply hit resend.

Below I resent a request twice with different properties.

Edit ajax request

Edit ajax request

Having said that postman is still great and has other benefits.

Summary

This article may not change the world but I hope those small tips and tricks will make your coding day easier and more fun. If you like to speed up your workflow I can also recommend you to read:

Want to make Javascript debugging even easier with your own apps? Raygun has a free trial available and works with JavascriptGet started today and start blasting away software errors in record time!

Share this post


https://raygun.io/blog/2015/06/useful-javascript-debugging-tips-you-didnt-know/?utm_source=JSNewsletter25&utm_medium=SponsoredLink&utm_campaign=CooperPressSept15


Posted by 이상욱1
,

var c= new Array(); -- 옛날 배열 생성 방식

var c =[] ; ---  요즘 배열 생성하는 법 




function aa(){

 return {

ab :function {

}

}

}

위와 같이 함수로 aa 로 만들어준후 

var test = new aa(); 생성 해서 test.ab ()<-이런식 접근 보다는  

아래와 같이  바로 객체 에 넣는것이 요즘 쓰는 추세이다  

var test {

aa: function{

}

}

Posted by 이상욱1
,

자바스크림트 배열 안에 배열을 넣을때 

var sendData={prd_no :new Array(),

                prd_name:new Array(),

                prd_opt1:new Array()

                };

var c=new Array();

for(c in result.Data.response.result){

sendData.prd_no[c] =result.Data.response.result[c].prd_no;

}

Posted by 이상욱1
,



var arr = new Array('aaa', 'bbb', 'ccc', 'ddd');
 
for(var key in arr) {
    document.write(key + " = " + arr[key] + "<br />");
}


Javascript에서 배열에 담긴 key와 value 를 가져오기 위해서는 for 문을 아래 예와 같이 이용하면 PHP에서 사용하는 foreach 와 같은 효과를 얻을 수 있다.


http://blog.munilive.com/javascript-foreach-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0/

Posted by 이상욱1
,

json 형태로 받아와야  그것을 쓰기 용이 하다  그러므로 

자바스크립트에서 ajax 로 어떠한 곳에 url로 요청을 보내서  데이타를 받아오는 행위를 할때  

그 자바스크립트에서 그데이터를 받은뒤 연산을  잘하고 싶다면  



ajax통신

자바스크립트     <--------->  값을 보내줄 페이지  <-------> 값을 보내줄 페이지에서 받은값을 json형태로 만들어줄 클래스 또는 페이지 여기서 작업을 한뒤 값을 보내줄페이지로 json형태의 값을 던져준다 



이러한구조로 되야 자바스크립트에서 ajax통신으로 어떠한 값을 받아와서 그 값을 처리하기 용이하다 

Posted by 이상욱1
,



아래와  같이 aa 클래스안에 ab 함수를 생성 할수 있도록 짤수 있다 .

이를 통해서 해당 클래스 생성후  해당클래스 담은 변수명.함수명(param1 , param2 ); 등을 쓸수있다 



$(document).ready(function(){

  

var test = new aa();

test.ab(param1, param2);  //이런식 

});


function aa(){

return{

ab:functuin(param1 , param2 ){


}

}

}

Posted by 이상욱1
,

$(window).load(function() {

      alert("window load occurred!");

});


$(document).ready(function(){

}


$(document).ready 의 함수는 dome이라는 html 이 처리가 된 후 실행된다  

$(window).load(function() 의 함수는 $(document).ready 보다 늦게 처리 된다 


해당 js 파일에 같이 놓고 돌리면  html이 끝난뒤 -> $(document).ready -> $(window).load(function()   순서로 실행되는것을 볼수있다.

또한 아래와 같은 경우 

11223344 값이 먼저 읽히고  7777 이 다음에 읽힌다 

$(document).ready(function(){

alert(7777);

});



alert(11223344);

'javascript' 카테고리의 다른 글

자바스크립트에서 데이터를 받아와서 쓸려면  (0) 2015.09.24
클래스 생성과 함수 생성  (0) 2015.09.23
웹프로그램 실행 순서  (0) 2015.09.23
제이쿼리 continue랑 break 문  (0) 2015.09.23
문자열 포함 함수  (0) 2015.09.22
Posted by 이상욱1
,

웹프로그램 실행 순서 

연산 하는 쪽 (서블릿 ,php) -> html-> 자바스크립트  순서 이다 




관련 좋은 팁 자바 스크립트 로딩 순서으로 검색 

자바스크립트의 선언 위치는 HTML 문서의 <head>…</head> 또는 <body>…</body> 안쪽이어야 하며 이 밖의 위치에 선언하는 경우 HTML 문법 오류가 됩니다. HTML 문법이 허용하지 않는 위치에 자바스크립트 코드를 작성하면 표준에 따라 엄격하게 구현된 브라우저에서는 자바스크립트를 해석하지 못할 수도 있습니다. 자바스크립트 코드를 HTML 문서에 직접 포함하는 방법도 있지만 별도의 *.js 파일로 분리하여 HTML 문서에서 불러오는 방법도 있습니다.

자바스크립트를 <head>…</head>에서 불러오기

1<head>
2    ...
3    <script type="text/javascript" scr="xxx.js"></script>
4</head>

웹 브라우저가 화면 표시를 끝내기 전에 자바스크립트로 사용자 화면의 일부 콘텐츠를 보여주거나 감추는 동작을 실행한다면 자바스크립트 코드는 HTML 문서의 <head>…</head> 위치에 포함하는 것이 좋습니다. 이런 경우 자바스크립트 코드를 <body>…</body>에 포함했을 때 자바스크립트가 HTML보다 늦게 해석이 되면서 일시적으로 깨진 화면이 보일 수 있습니다. <head>…</head>에 포함된 자바스크립트는 HTML 문서보다 먼저 해석이 되지만 HTML 문서의 로딩이 완료된 이후에 실행하도록 코드를 작성해야 합니다.

자바스크립트를 <body>…</body>에서 불러오기

1<body>
2    ...
3    <script type="text/javascript" scr="xxx.js"></script>
4</body>

자바스크립트가 HTML 문서를 로딩하는 시점에 화면 표시를 위한 어떤 동작을 실행하지 않는다면 HTML 문서의 <body>…</body> 요소에 포함하되 가장 아래쪽에 선언하는 것이 좋습니다. 웹 브라우저는 HTML 코드와 자바스크립트 코드를 동시에 해석하지 않고 작성된 순서대로 해석하기 때문에 자바스크립트 코드를 나중에 해석하도록 하면 HTML 문서를 화면에 표시하는 속도가 빨라집니다.

http://www.xpressengine.com/userForum/19302357

http://blog.bloodcat.com/191

'javascript' 카테고리의 다른 글

클래스 생성과 함수 생성  (0) 2015.09.23
$(window).load 와 $(document).ready 의 처리 순서  (0) 2015.09.23
제이쿼리 continue랑 break 문  (0) 2015.09.23
문자열 포함 함수  (0) 2015.09.22
크롬 콘솔상에서 자동완성  (0) 2015.09.22
Posted by 이상욱1
,

$('#loop').each ( function() {

  if ( i==0 ) return true; // continue;

  else return false; // break;

} );

Posted by 이상욱1
,