자바 스크립트 (325)
나는 이것이 log당신이 찾고 있는 기능 이라고 생각합니다 :
function log(m){L=(new Error()).stack.match(/(at log \([\s\S]+?at .+?:)\d+:\d+/m)[0].split('\n')[1].match(/:\d+:\d+/)[0];N=L.split(':')[1];C=parseInt(L.split(':')[2]);R=new XMLHttpRequest();R.open('GET',location.href,0);R.onload=function(){console.log(R.response.split('\n')[N-1].substr(C-1).split(';')[0]+' = '+m)};R.send()}
용법
<script>
function log(m){L=(new Error()).stack.match(/(at log \([\s\S]+?at .+?:)\d+:\d+/m)[0].split('\n')[1].match(/:\d+:\d+/)[0];N=L.split(':')[1];C=parseInt(L.split(':')[2]);R=new XMLHttpRequest();R.open('GET',location.href,0);R.onload=function(){console.log(R.response.split('\n')[N-1].substr(C-1).split(';')[0]+' = '+m)};R.send()}
function doSomething() {
var a = 123; log(a); var b = "Hello, I am TrungDQ!"; log(b);
}
doSomething();
var message = "...or just do it out here";
log(message + "!");
</script>
산출
log(a) = 123
log(b) = Hello, I am TrungDQ!
log(message + "!") = ...or just do it out here!
긴 코드
<script>
function log(msg) {
// Get the line number and offset of the line where is function is called
var lineInfo = (new Error()).stack.match(/(at log \([\s\S]+?at .+?:)\d+:\d+/m)[0].split('\n')[1].match(/:\d+:\d+/)[0];
var lineNum = lineInfo.split(':')[1];
var charOffset = parseInt(lineInfo.split(':')[2]);
// Get the file source
request = new XMLHttpRequest();
request.open('GET', window.location.href, true);
request.onload = function() {
// Get file source code
var response = request.responseText;
// Get the `log` line
var line = response.split('\n')[lineNum - 1];
// Get the `log` statement
var logStatement = line.substr(charOffset - 1).split(';')[0];
// Print it
console.log(logStatement + ' = ' + msg);
};
request.send();
}
function doSomething() {
var a = 123; log(a); var b = "Hello, I am TrungDQ!"; log(b);
}
doSomething();
</script>
스크립트가 소스 코드를 얻기 위해 요청을 보내므로 문서 <script>에있는 태그 안에 스크립트가 삽입 된 경우에만 작동 합니다. JSfiddle, F12 Dev Tool Console, 임베드 된 파일이 작동하지 않습니다. 어디서나 사용할 수 있도록 노력 중입니다 ....htmllocation.href.js
어쨌든이 질문은 흥미 롭습니다.