[Javascript] Closure

Found a very good article in Chinese from the blog of Ruanyifeng which talking about the closure of javascript.

Before learning closure, it is better to understand the variable scope.

Learn by doing (all examples with # have been tested, try them):

  • #1 example
  • Global variable :

    var v1 = 1;
    function f1() {
      console.log(v1); // Display 1 in console
    }
    
  • #2 example
  • Local variable :

    function f2() {
      var v2 = 1;
    }
    console.log(v2); // Can't find variable:v2
    

    So local variable cannot be used outside of a function.

    Attention!
    There is an exception, local variable defined in function must use the “var” command, or it will be considered as a global variable, see an example:

  • #3 example
  • function f3() {
      v3 = 1;
    }
    f3(); // call function f3, the variable will be initialized 
    console.log(v3); // Display 1 in console
    

    Continue reading

    Advertisements

    [Javascript] valueOf Object method

    Returns the primitive value of the specified object.
    返回指定对象的基础类型。

    object.valueOf()
    
      Parameters : 参数
    • Array
      Returns the array instance.
    • Boolean
      The boolean value.
    • Date
      The stored time value in milliseconds midnight, January 1, 1970 UTC.
    • Function
      The function itself.
    • Number
      The numeric value.
    • Object
      The object itself. By default.
    • String
      The string value.
      Example : 例子

    Continue reading

    [Javascript] map Array method

    Map is a method for javascript Array.

    It calls a defined callback function on each element of an array, and returns an array that contains the results.
    map函数对数组中每个元素调用一个已定义的回调方法。

    yourArray.map(callbackfn[, thisArg])
    
      Parameters : 参数
    • yourArray
      Required. An array object. 数组(必须)
    • callbackfn
      Required. A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. 回调函数,最多可接受三个参数(必须)
    • thisArg
      Optional. An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. 关联到回调函数的一个对象(可选)
      Return : 返回值
      A new array in which each element is the callback function return value for the associated original array element. 一个重新生成的数组

    Continue reading

    [Javascript] hasOwnProperty

    This post is just to remind me that javascript objects have a basic function hasOwnProperty which could determine whether an object has a property with a specified name.
    判断对象是否包含相应的属性。

    object.hasOwnProperty(proName)
    
      Parameters : 参数
    • object
      Required. Instance of an object. 对象的一个实例(必须)
    • proName
      Required. String value of a property name. 属性名(必须)
      Return : 返回值
    • true, if object has a property of the specified name
    • false, if it does not
      Example :
    var obj = {p1:"v1", p2:"v2"}
    if(obj.hasOwnProperty(p1)) {
      console.log("Yes, I have the property p1");
    } else {
      console.log("Sorry, I do not have this property ");
    }
    

    If everything is ok, your console will display “Yes, I have the property p1”.

    Ref. MSDN

    [JS practice] Pluck function(读取数组中相同属性的项目)

    Title :
    Pluck (读取数组中相同属性的项目)

    Description:

    Implement pluck, which takes an array of objects and a property name, and returns an array containing the named property of each object.

    实现一个pluck方法,输入的参数为一个包含N个对象的数组和一个字符串,输出数组中包含的字符串所对应的对象的值,如果没有则返回undefined。
    我用到了循环,不过似乎还有更简单的方法哦 🙂

    For example:

    pluck([{a:1}, {a:2}], 'a') // -> [1,2]
    

    If an object is missing the property, you should just leave it as undefined in the output array.

    Continue reading

    [JS practice] Count characters in your string (计算string里字符出现的次数)

    Title :
    Count characters in your string (计算string里字符出现的次数)

    Description :
    The main idea is to count all the occuring characters(UTF-8) in string. If you have string like this aba then the result should be { ‘a’: 2, ‘b’: 1 }

    What if the string is empty ? Then the result should be empty object literal {}

    Continue reading

    [Closure Tools] Closure Linter – A JavaScript style checker and fixer

    Found a very good and open source tool which is provided by google to check javascript code.

    Closure Linter

    Find the home page here :

    https://code.google.com/p/closure-linter/

    How to install and use it :

    https://developers.google.com/closure/utilities/docs/linter_howto?csw=1

    What’s important for a javascript developer is :

    – The code style

    http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

    Javascript – enable Enter key in your keyboard

    Bind a function which is called functionWasCalled to the Enter key of your keyboard :

    HTML :

    <html>
      <body>
        <input id="idOfInput" type="text" />
      </body>
    </html>

    Javascript :

    $('#idOfInput').die('keypress').live('keypress', 
        { instance : self }, function (e) {
             if ( e.keyCode == 13 ){ self.functionWasCalled(e);}
     });

    Javascript – get size of an object

    In javascript, we don’t have a method who could get the size of an object directly. But we could consider it as an array, and get the size of the array.

    Method 1 :

    size1 = Object.keys(object).length

    Method 2 :

    size2 = Object.values(object).length

    Method 3 :

    We could wirte a function, I will give it later