|
查看: 2368|回复: 23
|
Javascript
[复制链接]
|
|
|
本帖最后由 偶是双子座 于 11-10-2011 01:17 AM 编辑
小弟我平时在公司有空的时候都会研究研究javascript,用javascript配合html和css来写一些简单的程式。一直都很想开一个javascript的讨论贴,和大家一起研究和分享javascript的技术,用法,心得等等。。 |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 10-4-2011 01:33 PM
|
显示全部楼层
本帖最后由 偶是双子座 于 13-6-2011 11:47 PM 编辑
虽然现在有很多javascript frameworks,但是有时候有些简单和常用的程式在javascript framework里面找不到。。
在这里先和大家分享下一些我常用的程式。希望大家也来分享下各自常用的程式
foreach
javascript没有foreach,每次要用for in来loop,然后每次都用i, j等的counter代码,如果太多nested for有时候会搞到有点乱水。。
在jQuery里面有一个.each的function,不过只限于array的用途,如果要用在json或其他object就不行了。所以就写了以下的程式。
源码:
- /*
- * mock foreach
- * problem: unable to perform break, continue and return operation. use "for in" instead.
- */
- function foreach( obj, callback ) {
- for ( var i in obj ) {
- var result = callback.call( this, obj[ i ], i );
- if ( result !== undefined ) { //to break the foreach
- return result;
- };
- }
- }
复制代码 用法:
- var meter = { "mm" : 0.001, "cm": 0.01, "m" : 1, "km" : 1000 };
- foreach( meter, function( factor, name ) {
- console.log( "5m == " + ( 5 / factor ) + name );
- } );
- /* output:
- 5m == 5000mm
- 5m == 500cm
- 5m == 5m
- 5m == 0.005km
- */
复制代码 |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 10-4-2011 02:38 PM
|
显示全部楼层
===, !== 和 ==,!= 的分别
本帖最后由 偶是双子座 于 3-6-2011 11:20 AM 编辑
一般上我们都比较长用到 == 和 != 来比较两个variables。 偶尔会看到 === 或 !==,到底它们的分别在于哪里呢?我不清楚大家上课的时候有没有教到这个,不过我的学院教的没有包裹这个,所以当我第一次遇到的时候就觉得很奇怪 。所以如果你学过,知道了,也不必奇怪为什么这么简单的东西也拿出来分享
其实 === 和 == 之间的分别很简单。== 比较 value;=== 比较 value 和 type。
看下以下的例子应该不难理解:
- console.log( 0 == false ); // true
- console.log( 0 === false ); // false
- console.log( "" == false ); // true
- console.log( "" === false ); // false
- console.log( 0 == "" ); // true
- console.log( 0 === "" ); // false
- console.log( 1 == "1" ); // true
- console.log( 1 === "1" ); // false
- console.log( null == undefined ); // true
- console.log( null === undefined ); // false
- console.log( 0 === 0 ); // true
- console.log( "" === "" ); // true
- console.log( null === null ); // true
- console.log( undefined === undefined ); // true
复制代码 所以当我们要比较 value 和 type又或者要很确定的比较那variables时,就必须用到===或!==
另外,有意点要提醒大家的。switch是用===来做比较的。-
- function test( val ) {
- switch ( val ) {
- case 1 :
- console.log( "1 numeric" );
- break;
-
- case "1" :
- console.log( "1 text" );
- break;
- case 0 :
- console.log( "0" );
- break;
- case "" :
- console.log( "empty string" );
- break;
- case null :
- console.log( "null" );
- break;
- case undefined :
- console.log( "undefined" );
- break;
- case false :
- console.log( "false" );
- break;
- case true :
- console.log( "true" );
- break;
- default :
- console.log( "none of above" );
- break;
- }
- }
- test( 1 ); // 1 numeric
- test( "1" ); // 1 text
- test( true ); // true
- test( 0 ); // 0
- test( "0" ); // none of above
- test( "" ); // empty string
- test( false ); // false
- test( null ); // null
- test( undefined ); // undefined
复制代码 |
|
|
|
|
|
|
|
|
|
|
发表于 10-4-2011 04:23 PM
|
显示全部楼层
多谢分享。
等我整理好了,我再来分享我的心得。 |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 10-4-2011 10:40 PM
|
显示全部楼层
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 11-4-2011 12:01 AM
|
显示全部楼层
加速coding的小提示。 ? : 和 || 的应用
本帖最后由 偶是双子座 于 11-4-2011 01:46 AM 编辑
“? :” 的应用相信大家都不陌生。如果你没用过,不清楚,没关系,现在我和你分享下
?:基本上就像if else一样,只是缩短了写法。- condition ? statement execute when condition true : statement execute when condition false
复制代码 比如:
- if ( name == "john" ) {
- console.log( "is john" );
- } else {
- console.log( "is not john" );
- }
- //可以写成
- name == "john" ? console.log( "is john" ) : console.log( "is not john" );
- //或者
- console.log( name == "john" ? "is john" : "is not john" );
复制代码 ==========================================================
|| 比较常见于比较两个variables,相等与 OR 的意思。在比较两个variables的同时,|| 其实会return一个value的。这是什么意思呢?请看以下例子。
例子:
- var a;
- var b;
- var c = 0;
- var d = 1;
- var e = 2;
- console.log( 0 || 1 ); // 1
- console.log( a || b ); // undefined
- console.log( a || c ); // 0
- console.log( a || d ); // 1
- console.log( d || e ); // 1
- console.log( e || d ); // 2
复制代码 在上面的例子里面,可以看见这种情况:当 ( value1 || value2 ) 时,如果value1是true(即不是 false, null, undefined, 0, "" )的话,它就会return value1;如果value1是false(即 false, null, undefined, 0, "" )的话,它就会return value2。
了解了这个,我们就可以应用这一点。
如:
- function fn( name ) {
- name = name || "john"; //如果call fn时,有pass name进来的话,name 就会 = name。如果没有,name 就会 = "john"
- }
- /* //相等与这样的写法:
- function fn( name ) {
- if ( name ) {
- name = name;
- } else {
- name = "john";
- }
- }
- */
复制代码 |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 11-4-2011 09:47 PM
|
显示全部楼层
in
本帖最后由 偶是双子座 于 11-4-2011 09:52 PM 编辑
in 除了用于for in之外,还可以用在检查object里面是否有某个property或者method。
用法:
- var meter = { "mm" : 0.001, "cm": 0.01, "m" : 1, "km" : 1000 };
- console.log( "m" in meter ); // true
- console.log( "cm" in meter ); // true
- console.log( "tm" in meter ); // false
复制代码 if ( property in object ) VS if ( object.property )
当你要确定某个property是否存在于某个object时,如果用“if ( object.property )”的话,就要注意了,因为如果object.property是 0, "", false, null 和 undefined 的话,if的condition就会是false了。 |
|
|
|
|
|
|
|
|
|
|
发表于 16-4-2011 12:44 AM
|
显示全部楼层
你遗漏了最重要的... 但看了你的代码你应该已经知道coding style的重要性了。
var x = false;
if(x != false)
{
console.log("something is wrong");
}
和
if(x != false){
console.log("something is wrong");
}
的分别...
其他语言没什么关系但Javascript本质上会自动完成一句syntax. |
|
|
|
|
|
|
|
|
|
|
发表于 16-4-2011 01:09 AM
|
显示全部楼层
|
|
|
|
|
|
|
|
|
|
发表于 16-4-2011 01:45 AM
|
显示全部楼层
回复 megablue
原来如此,谢谢.
chrizyuen2 发表于 16-4-2011 01:09 AM 
不是反话吧 
我分享一下我的学习心得吧...
学Javascript 最重要的步骤是... 要一直学习... 很多时候你学的都是错但自以为学会/对了。
我一开始也是东学一点西学一点... 最重要的是让自己有兴趣学下去。
后来ajax开始盛行我才发觉自己学的懂得太少了就决定重新学起。读了不少javascript的书籍,其中一本最有印象的就是Javascript Bible (没记错应该是Fifth Edition)。
也看了不少的Javascript tech talks... 其中印象最深的有Douglas Crockford (JSON 发明者) 和 John Resig (jquery 发明者).
一直学习。。。纠正自己的错误观念... 再一直学...
javascript 可以说是最被看轻的编程语言;但也同样的最强大的语言。 |
|
|
|
|
|
|
|
|
|
|
发表于 16-4-2011 05:24 PM
|
显示全部楼层
|
很少写JABASCRIPT。。。呵呵。。多数是在网上下载代码,或者用jquery. |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 16-4-2011 07:21 PM
|
显示全部楼层
你遗漏了最重要的... 但看了你的代码你应该已经知道coding style的重要性了。
var x = false;
if(x ! ...
megablue 发表于 16-4-2011 12:44 AM 
的确,coding的习惯也是蛮重要的一部分,除了让code容易阅读之外,可以避免犯下一些不该犯的错误。除了上述的一个例子还有别的,向json object里面的名字:
- var obj = {
- "name" : "value" //正确的写法
- }
- //vs
- var obj = {
- name : "value" //虽然说这样写也没问题,但是尽量在name加上""才是正确的写法。因为name不限制于单字。数目,keywords,多个word都可以应用。
- }
复制代码 另外,其实我觉得我漏了很多的东西,所以才开这个贴让大家研究和讨论。
我很少看书,很懒惰看书。。通常都是看别人写的code,上网google和看别人的教学来学习的。在学院里面学的Programming真的很皮毛而已,很多东西都要自己学习,免不了遗漏了许多重要的东西。
很少写JABASCRIPT。。。呵呵。。多数是在网上下载代码,或者用jquery.
Mr.Ling 发表于 16-4-2011 05:24 PM 
其实如果只是一般的运用是没什么关系啦,了解基本的写法就ok咯。但是如果要写一些像jquery或其他framework或plug-in那样的东西,一定要对javascipt有相当的了解。
现在很多的都是拿开源的code来用就是了,不过我比较想知道他们如何写出这么厉害的东西,有时候会研究他们的code,了解他们的原理,从中学习。 |
|
|
|
|
|
|
|
|
|
|
发表于 18-4-2011 03:00 PM
|
显示全部楼层
本帖最后由 chrizyuen2 于 18-4-2011 03:47 PM 编辑
- <option style="font-
- weight:bold">blah</option>
复制代码
Chrome:FAIL, Firefox:OK, Opera:FAIL
- <option style="color:red">blah</option>
复制代码 All browser:OK
老实说,我真的被吓倒。  |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 18-4-2011 03:12 PM
|
显示全部楼层
All browser:OK
老实说,我真的被吓倒。
chrizyuen2 发表于 18-4-2011 03:00 PM 
抱歉,不明白你要表达的东西。。 |
|
|
|
|
|
|
|
|
|
|
发表于 18-4-2011 03:49 PM
|
显示全部楼层
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 18-4-2011 04:19 PM
|
显示全部楼层
回复 17# chrizyuen2
这个我倒没有试过。貌似只能换颜色和背景。
另外,请尽量讨论有关javasript的话题吧。 |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 3-6-2011 11:11 AM
|
显示全部楼层
Ten Oddities And Secrets About JavaScript (转载自Smashing Magazine)
简介:
1. Null is an Object
2. NaN is a Number
3. An Array With No Keys == False (About Truthy and Falsy)
4. replace() Can Accept a Callback Function
5. Regular Expressions: More Than Just Match and Replace
6. You Can Fake Scope
7. Functions Can Execute Themselves
8. Firefox Reads and Returns Colors in RGB, Not Hex
9. 0.1 + 0.2 !== 0.3
10. Undefined Can Be Defined
全文按这里:Smashing Magazine Ten Oddities And Secrets About JavaScript (转载自Smashing Magazine)
Smashing Magazine是一个不错的网站,经常会分享一些有用的IT资讯。 |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 14-6-2011 12:09 AM
|
显示全部楼层
Class and Sub Classes
本帖最后由 偶是双子座 于 14-6-2011 06:44 PM 编辑
有跟帖的朋友可能会留意到之前贴过的一些帖子不见了,因为我最近从新修改着一些常用的code,所以拿掉了一些我个人觉得写得不完整的。
最近钻研着John Resig一本叫做"Secrets of the JavaScript Ninja"的书。里面很多很advanced的javascript用法,喜欢javascript的朋友不妨去找来看看。不过,这本书是还不完整的,作者还在编辑中。
参考了这一本书和一些网上的例子,我从新编辑过之前贴过的简单的JQuery Class Plugin。之前的版本太过简单,而且存在着一个问题,就是subclass instanceof superclass的时候是不正确的,现在这个版本纠正了这个问题,也比起之前的多了一些功能,源码也比较复杂。暂时来说,这个版本还不是很完整,还在测试中。。
先来分享源码,已经upload去jquery plugin( http://plugins.jquery.com/project/jClass ),迟些再贴应用的方法。。
- /*!
- * Simple Class and SubClass handler ( optional for jquery plugin )
- *
- * Copyright (c) 2011, Meng Soon
- * Licensed under MIT
- * http://mengsoon.wordpress.com/license
- *
- * version: 0.3.2
- *
- */
- ( function( window, undefined ) {
-
- //get jQuery from window if it exist
- var $ = window.jQuery ? window.jQuery : {};
-
- //use jquery each or an alternative
- $.each = $.each || function( object, callback ) {
- //loop each items in object
- for ( var index in object ) {
- //call callback function
- callback.call( object, index, object[ index ] );
- }
- }
-
- //use jquery extend or an alternative. jquery before 1.0.4, $.extend is not reliable
- $.extend = ( $.extend && !( ( /^1\.0\..*$/.test( $.fn.jquery ) ) || ( /^\$.*\$/.test( $.fn.jquery ) ) ) ? $.extend : undefined ) || function( deep, target ) {
- var objects;
-
- if ( Object.prototype.toString.call( deep ) != '[object Boolean]' ) {
- //bind false to deep and recall function if first parameter is not boolean
- return arguments.callee.apply( this, [ false ].concat( Array.prototype.slice.call( arguments ) ) );
- } else if ( !( ( objects = Array.prototype.slice.call( arguments, 2 ) ).length ) ) {
- //bind $ to target, bind target to third parameter and recall function if no third parameter exist
- return arguments.callee.call( this, deep, $, target );
- }
-
- //loop for each parameters start from 3rd
- $.each( objects, function( index, object ) {
- //loop each properties
- $.each( object, function( index, value ) {
- //replace value
- target[ index ] = typeof value == 'object' && deep ? arguments.callee.call( this, deep, target[ index ], value ) : value;
- } );
- } );
-
- //return updated target
- return target;
- }
-
- //extend jquery utility
- $.extend( {
- //use jquery isFunction or an alternative
- isFunction : $.isFunction || function( fn ) {
- return Object.prototype.toString.call( fn ) == '[object Function]';
- },
-
- //use jquery isArray or an alternative
- isArray: $.isArray || function( array ) {
- return Object.prototype.toString.call( array ) == '[object Array]';
- }
- } );
-
- //main function
- var jClass = ( function() {
-
- //private cunstruct class indicator, prevent init class execute when inherit from parent on class construction
- var construct = false;
-
- return function( structure, Parent ) {
- //default parent to Object if not pass in
- Parent = Parent || Object;
-
- //set each method's _super to call parent's method
- $.each( structure, function( index, method ) {
- //filter by function
- if ( $.isFunction( method ) ) {
- //set the method's _super to call the parent's method
- //ensure always call the latest version of the parent method
- method._super = function() {
- //get the method
- var fn = Parent.prototype[ index ];
-
- //call and return the method
- //return the _super object if not a function, or probably 'undefined'
- return $.isFunction( fn ) ? fn.apply( this, arguments ) : fn;
- }
- }
- } );
-
- //generate a class
- function Class() {
- //prevent execute of parent's init when new class is constructing
- //check is init a function
- if ( !construct && $.isFunction( this.init ) ) {
- //call init function
- this.init.apply( this, arguments );
- }
- }
-
- //inherit from parent
- construct = true;
- Class.prototype = new Parent();
- construct = false;
-
- //extend Class.prototype to override methods and properties
- $.extend( Class.prototype, structure, {
-
- //override constructor
- constructor: Class,
-
- //create a general _super to call parent's method
- //use parent's _super if exist, prevent redundant
- _super: Class.prototype._super || function() {
- //get the method's _super function created above
- var fn = arguments.callee.caller._super;
-
- //call and return the method
- //return the _super object if not a function, or probably 'undefined'
- return $.isFunction( fn ) ? fn.apply( this, arguments ) : fn;
- }
-
- } );
-
- //extebd class object, add additional utilities
- $.extend( Class, {
-
- //make this class extandable
- extend: ( function( fn ) {
- //return a new function with binded parent class
- return function( structure ) {
- //execute the function with current class as parent
- return fn.call( this, structure, Class );
- };
- //pass in the main function
- } )( arguments.callee ),
-
- //allow to attach new method and override existing method in a class
- //this function will cater for the method calling _super
- method: function( method, fn, overload ) {
-
- ( function( c ) {
-
- //check is method exist and overload is true
- if ( method in c && overload === true ) {
- //overload method
- Class.overload( method, fn );
- } else {
- //set the _super, if existing method exist, use the existing _super instead
- fn._super = $.isFunction( c[ method ] ) ? c[ method ]._super : function() {
- //get the method
- var fn = Parent.prototype[ method ];
-
- //call and return the method
- //return the _super object if not a function, or probably 'undefined'
- return $.isFunction( fn ) ? fn.apply( this, arguments ) : fn;
- };
-
- //override method
- c[ method ] = fn;
- }
-
- } )( Class.prototype );
- },
-
- //allow the class overload methods
- //NOTE: only able to overload with different numbers of parameter
- overload: function( method, fn ) {
- //cache original method
- var old = Class.prototype[ method ];
-
- //set the new method _super
- fn._super = old && old._super;
-
- //replace and return new method
- return Class.prototype[ method ] = function() {
-
- //call matched method and return result
- return fn.length == arguments.length ?
-
- //call new function if parameters length match
- fn.apply( this, arguments ) :
- //check is original method is a function, prevent error
- $.isFunction( old ) ?
-
- //call original method
- old.apply( this, arguments ) :
- //return old if not match
- old;
- };
- },
-
- //multiple overload
- overloads: function( methods ) {
- //go through each methods
- for ( var method in methods ) {
- //list of functions
- var fns = methods[ method ];
-
- //convert to array if it is not array
- fns = $.isArray( fns ) ? fns : [ fns ];
-
- //overload method with each fn
- $.each( fns, function( index, fn ) {
- Class.overload( method, fn );
- } );
- }
- },
-
- //allow the class implement interfaces
- //extend a class with another class or object
- implement: function() {
- //get all pass in arguments
- var interfaces = Array.prototype.slice.apply( arguments );
-
- //process each interface
- $.each( interfaces, function( index, object ) {
- //make sure is not undefined
- if ( object !== undefined ) {
- //create new object is it is a class
- object = object.prototype ? new object() : object;
-
- //extend class's prototype
- $.extend( Class.prototype, object, {
- //prevent constructor and _super to be overrided
- constructor: Class.prototype.constructor,
- _super: Class.prototype._super
- } );
- }
- } );
- }
-
- } );
-
- //return the class function
- return Class;
- }
- } )();
-
- //provide public access
- if ( window.jQuery ) {
- //extend to jquery library if exist
- $.extend( {
- jClass: jClass
- } );
- } else {
- //or else set Class to a global Class
- window.jClass = jClass;
- }
-
- } )( window );
复制代码 |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 14-6-2011 06:48 PM
|
显示全部楼层
上面贴的源码已经更新过了。
Features:
- Provided easy access to superclass method by simply call 'this._super()'.
- Support for multiple levels of subclasses.
- Class can be easily extended.
- Support for overloads methods and implements interfaces.
用法:
Class creation
- var Person = $.jClass( {
- //init will auto call when a new object of the class is initialize
- init: function( name ) {
- this.name = name;
- },
- greet: function() {
- return "Hi, I'm " + this.name ;
- }
- } );
- var john = new Person( 'John' );
- alert( john.greet() ); //Hi, I'm John
复制代码
Extend Class
- var Ninja = $.jClass( {
- greet: function() {
- return 'Yihaaa!!';
- }
- }, Person );
- var resig = new Ninja( 'Resig' );
- alert( resig.greet() ); //Yihaaa!!
复制代码
Alternative way to extend class
- var Samurai = Person.extend( {
- greet: function() {
- return 'Ha!';
- }
- } );
- var mike = new Samurai( 'Mike' );
- alert( mike.greet() ); //Ha!
复制代码
Access superclass method
- var Shogun = Person.extend( {
- greet: function() {
- //or you can access by just call this._super()
- return this._super.apply( this, arguments ) + ". I'm the shogun";
- }
- } );
- var bob = new Shogun( 'Bob' );
- alert( bob.greet() ); //Hi, I'm Bob. I'm the shogun
复制代码
Multiple level of subclass calling super class method
- var GreatShogun = Shogun.extend( {
- greet: function() {
- return this._super.apply( this, arguments ) + ". The Great Shogun";
- }
- } );
- var smith = new GreatShogun( 'Smith' );
- alert( smith.greet() ); //Hi, I'm Smith. I'm the shogun. The Great Shogun
复制代码
Implement interfaces
- Person.implement( {
- walk: function() {
- return this.name + ' is walking';
- },
-
- run: function() {
- return this.name + ' is running';
- }
- } );
- alert( john.walk() ); //John is walking
- alert( resig.run() ); //Resig is running
- alert( bob.run() ); //Bob is running
- alert( smith.run() ); //Smith is running
复制代码
Overloads method
- Person.overload( 'greet', function( name ) {
- return 'Hi ' + name;
- } );
- alert( john.greet() ); //Hi, I'm John
- alert( john.greet( 'Resig' ) ); //Hi Resig
- alert( bob.greet( 'John' ) ); //Hi John. I'm the shogun
- alert( smith.greet( 'John' ) ); //Hi John. I'm the shogun. The Great Shogun
复制代码
Overloads multiple methods
- Person.overloads( {
- run: [ function( suffix ) {
- return this.run() + ' ' + suffix;
- }, function( prefix, suffix ) {
- return prefix + ' ' + this.run( suffix );
- } ],
-
- walk: function( suffix ) {
- return this.walk() + ' ' + suffix;
- }
- } );
- alert( john.walk( 'slowly' ) ); //John is walking slowly
- alert( resig.run( 'fast' ) ); //Resig is running fast
- alert( bob.run( 'Looks, ', 'very fast' ) ); //Looks, Bob is running very fast
复制代码
Modify method without loss the superclass method call
- GreatShogun.method( 'greet', function() {
- return this._super.apply( this, arguments ) + ". The Great Great Shogun!!";
- } );
- alert( smith.greet() ); //Hi, I'm Smith. I'm the shogun. The Great Great Shogun!!
复制代码 |
|
|
|
|
|
|
|
|
|
|
发表于 14-6-2011 07:04 PM
|
显示全部楼层
感謝樓主和各位大大無私分享 |
|
|
|
|
|
|
|
|
| |
本周最热论坛帖子
|