你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?
在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。
HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性
尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。
你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?
在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。
HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性
尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。
当前回答
也许对某些人来说有点明显…
安装Firebug并使用console.log("hello")。这比使用随机alert();好多了,我记得几年前我经常这样做。
其他回答
Function.toString()(隐性):
function x() {
alert("Hello World");
}
eval ("x = " + (x + "").replace(
'Hello World',
'STACK OVERFLOW BWAHAHA"); x("'));
x();
函数在JavaScript中是第一类公民:
var passFunAndApply = function (fn,x,y,z) { return fn(x,y,z); };
var sum = function(x,y,z) {
return x+y+z;
};
alert( passFunAndApply(sum,3,4,5) ); // 12
函数式编程技术可以用来编写优雅的javascript。
特别是,函数可以作为参数传递,例如Array.filter()接受回调:
[1, 2, -1].filter(function(element, index, array) { return element > 0 });
// -> [1,2]
你也可以声明一个“private”函数,它只存在于特定函数的作用域中:
function PrintName() {
var privateFunction = function() { return "Steve"; };
return privateFunction();
}
私有方法
对象可以有私有方法。
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
// A private method only visible from within this constructor
function calcFullName() {
return firstName + " " + lastName;
}
// A public method available to everyone
this.sayHello = function () {
alert(calcFullName());
}
}
//Usage:
var person1 = new Person("Bob", "Loblaw");
person1.sayHello();
// This fails since the method is not visible from this scope
alert(person1.calcFullName());
JavaScript被认为非常擅长于暴露它的所有对象,所以不管它的窗口对象本身。
因此,如果我想用JQuery/YUI div弹出窗口覆盖浏览器警报,它也接受字符串作为参数,可以简单地使用下面的代码片段。
function divPopup(str)
{
//code to show the divPopup
}
window.alert = divPopup;
有了这个更改,所有对alert()的调用都将显示新的基于div的弹出窗口,而不是浏览器特定的警报。
闭包:
function f() {
var a;
function closureGet(){ return a; }
function closureSet(val){ a=val;}
return [closureGet,closureSet];
}
[closureGet,closureSet]=f();
closureSet(5);
alert(closureGet()); // gives 5
closureSet(15);
alert(closureGet()); // gives 15
这里的闭包并不是所谓的解构赋值([c,d] =[1,3]等价于c=1;d=3;)但事实上,在closureGet和closurereset中出现的a仍然指向同一个变量。即使在closureSet已经分配了一个新值之后!