Category Archives: JS

闭包(closure)

一、什么是闭包?

“官方”的解释是:闭包是一个拥有许多变量和绑定了这些变量的环境的表达式(通常是一个函数),因而这些变量也是该表达式的一部分。 相信很少有人能直接看懂这句话,因为他描述的太学术。其实这句话通俗的来说就是:JavaScript中所有的function都是一个闭包。不过一般来说,嵌套的function所产生的闭包更为强大,也是大部分时候我们所谓的“闭包”。看下面这段代码:

function a() {
    var i = 0;
    function b() {
        alert(++i);
    }
    return b;
}
var c = a();
c();

这段代码有两个特点:

  1. 函数b嵌套在函数a内部;
  2. 函数a返回函数b。

引用关系如图:

jsclosure

这样在执行完var c=a()后,变量c实际上是指向了函数b,b中用到了变量i,再执行c()后就会弹出一个窗口显示i的值(第一次为1)。这段代码其实就创建了一个闭包,为什么?因为函数a外的变量c引用了函数a内的函数b,就是说:

当函数a的内部函数b被函数a外的一个变量引用的时候,就创建了一个我们通常所谓的“闭包”。

让我们说的更透彻一些。所谓“闭包”,就是在构造函数体内定义另外的函数作为目标对象的方法函数,而这个对象的方法函数反过来引用外层函数体中的临时变量。这使得只要目标 对象在生存期内始终能保持其方法,就能间接保持原构造函数体当时用到的临时变量值。尽管最开始的构造函数调用已经结束,临时变量的名称也都消失了,但在目 标对象的方法内却始终能引用到该变量的值,而且该值只能通这种方法来访问。即使再次调用相同的构造函数,但只会生成新对象和方法,新的临时变量只是对应新 的值,和上次那次调用的是各自独立的。

为了更深刻的理解闭包,下面让我们继续探索闭包的作用和效果。

二、闭包有什么作用和效果?

简而言之,闭包的作用就是在a执行完并返回后,闭包使得Javascript的垃圾回收机制GC不会收回a所占用的资源,因为a的内部函数b的执行需要依赖a中的变量。这是对闭包作用的非常直白的描述,不专业也不严谨,但你一定能看懂。理解闭包需要循序渐进的过程。 在上面的例子中,由于闭包的存在使得函数a返回后,a中的i始终存在,这样每次执行c(),i都是自加1后alert出i的值。

那么我们来想象另一种情况,如果a返回的不是函数b,情况就完全不同了。因为a执行完后,b没有被返回给a的外界,只是被a所引用,而此时a也只会被b引用,因此函数a和b互相引用但又不被外界打扰(被外界引用),函数a和b就会被GC回收。(关于Javascript的垃圾回收机制将在后面详细介绍)

三、闭包的微观世界

如果要更加深入的了解闭包以及函数a和嵌套函数b的关系,我们需要引入另外几个概念:函数的执行环境(excution context)、活动对象(call object)、作用域(scope)、作用域链(scope chain)。以函数a从定义到执行的过程为例阐述这几个概念。

  1. 定义函数a的时候,js解释器会将函数a的作用域链(scope chain)设置为定义a时a所在的“环境”,如果a是一个全局函数,则scope chain中只有window对象。
  2. 执行函数a的时候,a会进入相应的执行环境(excution context)
  3. 在创建执行环境的过程中,首先会为a添加一个scope属性,即a的作用域,其值就为第1步中的scope chain。即a.scope=a的作用域链。
  4. 然后执行环境会创建一个活动对象(call object)。活动对象也是一个拥有属性的对象,但它不具有原型而且不能通过JavaScript代码直接访问。创建完活动对象后,把活动对象添加到a的作用域链的最顶端。此时a的作用域链包含了两个对象:a的活动对象和window对象。
  5. 下一步是在活动对象上添加一个arguments属性,它保存着调用函数a时所传递的参数。
  6. 最后把所有函数a的形参和内部的函数b的引用也添加到a的活动对象上。在这一步中,完成了函数b的的定义,因此如同第3步,函数b的作用域链被设置为b所被定义的环境,即a的作用域。

到此,整个函数a从定义到执行的步骤就完成了。此时a返回函数b的引用给c,又函数b的作用域链包含了对函数a的活动对象的引用,也就是说b可以访问到a中定义的所有变量和函数。函数b被c引用,函数b又依赖函数a,因此函数a在返回后不会被GC回收。

当函数b执行的时候亦会像以上步骤一样。因此,执行时b的作用域链包含了3个对象:b的活动对象、a的活动对象和window对象,如下图所示:

http://www.felixwoo.com/wp-content/uploads/attachments/200712/11_110522_scopechain.jpg

如图所示,当在函数b中访问一个变量的时候,搜索顺序是:

  1. 先搜索自身的活动对象,如果存在则返回,如果不存在将继续搜索函数a的活动对象,依次查找,直到找到为止。
  2. 如果函数b存在prototype原型对象,则在查找完自身的活动对象后先查找自身的原型对象,再继续查找。这就是Javascript中的变量查找机制。
  3. 如果整个作用域链上都无法找到,则返回undefined。

小结,本段中提到了两个重要的词语:函数的定义执行。文中提到函数的作用域是在定义函数时候就已经确定,而不是在执行的时候确定(参看步骤1和3)。用一段代码来说明这个问题:

function f(x) {
    var g = function () { return x; }
    return g;
}
var h = f(1);
alert(h());

这段代码中变量h指向了f中的那个匿名函数(由g返回)。

  • 假设函数h的作用域是在执行alert(h())确定的,那么此时h的作用域链是:h的活动对象->alert的活动对象->window对象。
  • 假设函数h的作用域是在定义时确定的,就是说h指向的那个匿名函数在定义的时候就已经确定了作用域。那么在执行的时候,h的作用域链为:h的活动对象->f的活动对象->window对象。

如果第一种假设成立,那输出值就是undefined;如果第二种假设成立,输出值则为1。

运行结果证明了第2个假设是正确的,说明函数的作用域确实是在定义这个函数的时候就已经确定了。

四、闭包的应用场景

  1. 保护函数内的变量安全。以最开始的例子为例,函数a中i只有函数b才能访问,而无法通过其他途径访问到,因此保护了i的安全性。
  2. 在内存中维持一个变量。依然如前例,由于闭包,函数a中i的一直存在于内存中,因此每次执行c(),都会给i自加1。
  3. 通过保护变量的安全实现JS私有属性和私有方法(不能被外部访问)推荐阅读:http://javascript.crockford.com/private.html私有属性和方法在Constructor外是无法被访问的
    function Constructor(...) {
        var that = this;
        var membername = value;
        function membername(...) {...}
    }

以上3点是闭包最基本的应用场景,很多经典案例都源于此。

五、Javascript的垃圾回收机制

在Javascript中,如果一个对象不再被引用,那么这个对象就会被GC回收。如果两个对象互相引用,而不再被第3者所引用,那么这两个互相引用的对象也会被回收。因为函数a被b引用,b又被a外的c引用,这就是为什么函数a执行后不会被回收的原因。

六、结语

理解JavaScript的闭包是迈向高级JS程序员的必经之路,理解了其解释和运行机制才能写出更为安全和优雅的代码。如果您对本文有任何的建议和疑问,欢迎留言

Private Members in JavaScript  http://javascript.crockford.com/private.html

闭包的概念、形式与应用http://www.ibm.com/developerworks/cn/linux/l-cn-closure/

闭包之美 http://www.ituring.com.cn/article/1317

理解C#闭包 http://www.cnblogs.com/jiejie_peng/p/3701070.html

Private Members in JavaScript

JavaScript is the world’s most misunderstood programming language. Some believe that it lacks the property of information hiding because objects cannot have private instance variables and methods. But this is a misunderstanding. JavaScript objects can have private members. Here’s how.

Objects

JavaScript is fundamentally about objects. Arrays are objects. Functions are objects. Objects are objects. So what are objects? Objects are collections of name-value pairs. The names are strings, and the values are strings, numbers, booleans, and objects (including arrays and functions). Objects are usually implemented as hashtables so values can be retrieved quickly.

If a value is a function, we can consider it a method. When a method of an object is invoked, the this variable is set to the object. The method can then access the instance variables through the this variable.

Objects can be produced by constructors, which are functions which initialize objects. Constructors provide the features that classes provide in other languages, including static variables and methods.

Public

The members of an object are all public members. Any function can access, modify, or delete those members, or add new members. There are two main ways of putting members in a new object:

In the constructor

This technique is usually used to initialize public instance variables. The constructor’s this variable is used to add members to the object.

function Container(param) {
    this.member = param;
}

So, if we construct a new object

var myContainer = new Container('abc');

then myContainer.member contains 'abc'.

In the prototype

This technique is usually used to add public methods. When a member is sought and it isn’t found in the object itself, then it is taken from the object’s constructor’s prototype member. The prototype mechanism is used for inheritance. It also conserves memory. To add a method to all objects made by a constructor, add a function to the constructor’s prototype:

Container.prototype.stamp = function (string) {
    return this.member + string;
}

So, we can invoke the method

myContainer.stamp('def')

which produces 'abcdef'.

Private

Private members are made by the constructor. Ordinary vars and parameters of the constructor becomes the private members.

function Container(param) {
    this.member = param;
    var secret = 3;
    var that = this;
}

This constructor makes three private instance variables: param, secret, and that. They are attached to the object, but they are not accessible to the outside, nor are they accessible to the object’s own public methods. They are accessible to private methods. Private methods are inner functions of the constructor.

function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;
}

The private method dec examines the secret instance variable. If it is greater than zero, it decrements secret and returns true. Otherwise it returns false. It can be used to make this object limited to three uses.

By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.

Privileged

A privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside. It is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.

Privileged methods are assigned with this within the constructor.

function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;

    this.service = function () {
        return dec() ? that.member : null;
    };
}

service is a privileged method. Calling myContainer.service() will return 'abc' the first three times it is called. After that, it will return null. service calls the private dec method which accesses the private secret variable. service is available to other objects and methods, but it does not allow direct access to the private members.

Closures

This pattern of public, private, and privileged members is possible because JavaScript has closures. What this means is that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. This is an extremely powerful property of the language. There is no book currently available on JavaScript programming that shows how to exploit it. Most don’t even mention it.

Private and privileged members can only be made when an object is constructed. Public members can be added at any time.

Patterns

Public

function Constructor()   {

this.membername =       value;

} Constructor.prototype.membername =    value;

Private

function Constructor()   {

var that = this;       var membername = value;function membername() {}

}

Note: The function statement

function       membername() {}

is shorthand for

var membername = function membername()    {};

Privileged

function Constructor()   {

this.membername = function () {};

}

from: http://www.crockford.com/javascript/private.html

jQuery – .bind(), .live(), .delegate(), .on() ( and also .unbind(), .die(), .undelegate(), .off() )

jQuery - .bind(), .live(), .delegate(), .on(), .off(), .undelegate(), die(), .unbind()

All these functions are used to attach an event handler function to the selected elements or selectors. In this article I will take you through all the four set of functions to get an idea of what it is.

To start with, let me list down all the functions with short description and release details.

 

Method Short Description Added In Deprecated In Removed In
.bind() Attach a handler to an event for the elements. 1.0
.unbind()
Remove a previously-attached event handler from the elements.
1.0
.live() Attach an event handler for all elements which match the current selector, now and in the future. 1.3 1.7 1.9
.die() Remove event handlers previously attached using .live() from the elements. 1.3 1.7 1.9
.delegate() Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. 1.4.2
.undelegate()
Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.
1.4.2
.on()
Attach an event handler function for one or more events to the selected elements.
1.7
.off() Remove an event handler. 1.7

Which function to use? confused Confused, Which one to use, jQuery .bind(), .live(), .delegate(), .on() - Shemeer let’s go through the below details then you will be in a good position to decide which one to use and when.

.bind() and .unbind()

The .bind() method is used to register an events to existing html elements and .unbind() method is used to remove events, that are registered by .bind() method.

Syntax:-

 

Method Syntax Available from version
.bind() .bind( eventType [, eventData ], handler(eventObject) ) 1.0
.bind( eventType [, eventData ], preventBubble )
1.4.3
.bind( events ) 1.4
Parameter details are given below,

  • eventType:- A string containing one or more DOM event types, such as “click” or “submit,” or custom event names.
  • eventData:- An object containing data that will be passed to the event handler.
  • handler(eventObject):- A function to execute each time the event is triggered.
  • preventBubble:- Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true.
  • events:- An object containing one or more DOM event types and functions to execute for them.
.unbind() .unbind( [eventType ] [, handler(eventObject) ] ) 1.0
.unbind( eventType, false ) 1.4.3
.unbind( event )
1.4
Parameter details are given below,

  • eventType:- A string containing a JavaScript event type, such as click or submit.
  • handler(eventObject): The function that is to be no longer executed.
  • false: Unbinds the corresponding ‘return false’ function that was bound using .bind( eventType, false ).
  • event: A JavaScript event object as passed to an event handler.

Sample : –

Collapse | Copy Code
 $( document ).ready(function() {
  $( "#foo" ).bind( "click", function( event ) {
    alert( "The mouse cursor is at (" +
      event.pageX + ", " + event.pageY +
      ")" );
  });
});

The above code will cause a click on the element with ID foo to report the page coordinates of the mouse cursor at the time of the click.

Read more from http://api.jquery.com/bind/, http://api.jquery.com/unbind/

.live() and .die()

.live() method is used to add event handler to elements that are currently available in the page or dynamically added to the page whereas .die() is used to remove any handler that has been attached with .live().

Note: .live() and .die() are removed from jQuery version 1.9.

Method Syntax Available from version
.live() .live( events, handler(eventObject) ) 1.3
.live( events, data, handler(eventObject) )
1.4
.live( events ) 1.4.3
Parameter details are given below,

  • events:- A string containing a JavaScript event type, such as “click” or “keydown.” As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names. If events is the only parameter then events will be A plain object of one or more JavaScript event types and functions to execute for them.
  • data:- An object containing data that will be passed to the event handler.
  • handler(eventObject):- A function to execute each time the event is triggered.
.die() .die( eventType [, handler ] ) 1.3
.die() 1.4.1
.die( events )
1.4.3
Parameter details are given below,

  • eventType:- A string containing a JavaScript event type, such as click or keydown.
  • events:- A plain object of one or more event types, such as click or keydown and their corresponding functions that are no longer to be executed.

Sample:-

Collapse | Copy Code
<a class="link">Link Static</a>
<button id="addmore" type="button">Add more</button> 

 $(document).ready(function() {
   $('#addmore').click(function() {
      $('body').append(' <a class="link">Link Dynamic</a>');
        return false; 
  }); 
   $("a.link").bind('click', function() {
      alert('I am clicked');
   });
  });

As per the above code, when ever we click on the hyper-link (<a>) it will show an alert message.. We can add hyper-links dynamically using the button. but dynamically added links will not have click event attached. To make it work for both static control and dynamic we need to rewrite the code using live() as below,

Collapse | Copy Code
<a class="link">Link Static</a>
<button id="addmore" type="button">Add more</button> 

 $(document).ready(function() {
   $('#addmore').click(function() {
      $('body').append(' <a class="link">Link Dynamic</a>');
        return false; 
  }); 
   $("a.link").live('click', function() {
      alert('I am clicked');
   });
  });

Now all the static and dynamically created links will have the alert method event attached.

Read more from http://api.jquery.com/live/, http://api.jquery.com/die/

.delegate() and .undelegate()

.delegate() method behaves in a similar fashion to the .live() method, but the major difference is that It attaches the event handler to the context , rather than the document. The .undelegate() method is a way of removing event handlers that have been bound using .delegate().

Method Syntax Available from version
.delegate() .delegate( selector, eventType, handler(eventObject) ) 1.4.2
.delegate( selector, eventType, eventData, handler(eventObject) )
1.4.2
.delegate( selector, events ) 1.4.3
Parameter details are given below,

  • selector:- A selector to filter the elements that trigger the event.
  • eventType:- A string containing one or more space-separated JavaScript event types, such as “click” or “keydown,” or custom event names
  • eventData:- An object containing data that will be passed to the event handler.
  • handler(eventObject):- A function to execute each time the event is triggered.
  • events:- A plain object of one or more event types and functions to execute for them.
.undelegate() .undelegate() 1.4.2
.undelegate( selector, eventType ) 1.4.2
.undelegate( selector, eventType, handler(eventObject) )
1.4.2
.undelegate( selector, events ) 1.4.3
.undelegate( namespace ) 1.6
Parameter details are given below,

  • selector:- A selector which will be used to filter the event results.
  • eventType:- A string containing a JavaScript event type, such as “click” or “keydown”.
  • handler(eventObject):- A function to execute at the time the event is triggered.
  • events:- An object of one or more event types and previously bound functions to unbind from them.
  • namespace:- A string containing a namespace to unbind all events from.

Sample :-

Collapse | Copy Code
$( "table" ).delegate( "td", "click", function() {
  $( this ).toggleClass( "chosen" );
});

Read more from http://api.jquery.com/delegate/, http://api.jquery.com/undelegate/

.on() and .off()

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. The .on() method provides all functionality required for attaching event handlers. The .off() method removes event handlers that were attached with .on().

Method Syntax Available from version
.on() .delegate( selector, eventType, handler(eventObject) ) 1.4.2
.delegate( selector, eventType, eventData, handler(eventObject) )
1.4.2
.delegate( selector, events ) 1.4.3
Parameter details are given below,

  • selector:- A selector to filter the elements that trigger the event.
  • eventType:- A string containing one or more space-separated JavaScript event types, such as “click” or “keydown,” or custom event names
  • eventData:- An object containing data that will be passed to the event handler.
  • handler(eventObject):- A function to execute each time the event is triggered.
  • events:- A plain object of one or more event types and functions to execute for them.
.off() .off( events [, selector ] [, handler(eventObject) ] ) 1.7
.off( events [, selector ] ) 1.7
Parameter details are given below,

  • selector:- A selector which should match the one originally passed to .on() when attaching event handlers.
  • events:- An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s).

Sample:-

Collapse | Copy Code
$("p").on("click",function(){
  alert("The paragraph was clicked.");
});

The above code will be attaching the specified event to all (current and future) <p>.

Below code block is taken from jQuery 1.7.1.

You can see that for all the above listed methods the .on() method is being “overloaded” with different signatures, which in turn changes how the event binding is wired-up. The .on() method bring a lot of consistency to the API and hopefully makes things slightly less confusing.

Collapse | Copy Code
bind: function( types, data, fn ) {
    return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
    return this.off( types, null, fn );
},

live: function( types, data, fn ) {
    jQuery( this.context ).on( types, this.selector, data, fn );
    return this;
},
die: function( types, fn ) {
    jQuery( this.context ).off( types, this.selector || "**", fn );
    return this;
},

delegate: function( selector, types, data, fn ) {
    return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
    return arguments.length == 1 ? 
        this.off( selector, "**" ) : 
        this.off( types, selector, fn );
},

// ... more code ...

Read more from http://api.jquery.com/on/, http://api.jquery.com/off/

Comparison

The .bind() method registers the type of event and an event handler directly to the DOM element. The .bind() doesn’t work for elements added dynamically that matches the same selector. This method is pretty easy and quick to wire-up event handlers. The shorthand methods like .click(), .hover(), etc make it even easier to wire-up event handlers. There is a performance issue while working with large selection as the method attaches the same event handler to every matched element in the selection.The attachment is done upfront which can have performance issues on page load.

The basic difference between .bind() and .live() is bind will not attach the event handler to those elements which are added/appended after DOM is loaded and there is only one event handler registered instead of the numerous event handlers that could have been registered with the .bind() method. When using .live() events always delegate all the way up to the document. This can affect performance if your DOM tree is deep. Chaining is not properly supported using .live() method. Using event.stopPropagation() is no longer helpful because the event has already delegated all the way up to the document. .live() method is deprecated as of jQuery 1.7 and removed from jQuery 1.9.

The .delegate() method is very powerful, The difference between .live() and .delegate() is, live function can’t be used in chaining. live function needs to be used directly on a selector/element. Also .delegate() works on dynamically added elements to the DOM where the selectors match. Chaining is supported correctly in .delegate().

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. Brings uniformity to the various event binding methods. but as the the way we call .on() method the behaviour also changes.

Note: If you are using jQuery 1.7+ then its advised to use .on() for attaching events to elements or selectors.

Conclusion

All the these jQuery functions are used to attach events to selectors or elements. Some methods performs better in some situations. If you are using jQuery 1.7+ then its advised to use .on() over all the event binding methods.

References

Summary

In this article I have given detailed explanation of jQuery methods that’s used for attaching/removing event handlers. I hope you have enjoyed this article and got some value addition to your knowledge.

from: http://www.codeproject.com/Articles/778374/JQUERY-JSON-and-Angular-Interview-questions

JQUERY, JSON and Angular Interview questions

What is Jquery ?

So will jquery replace javascript ?

So how do we use these reusable jquery libraries?

What is CDN (Content delivery network)?

For Jquery files which are the popular CDN’s?

How can we reference local Jquery files if CDN fails?

What is the difference between Jquery.js and Jquery.min.js file?

When should we use jquery.js over jquery.min.js ?

What is the use jquery.vsdoc.js ?

How does the basic syntax of Jquery looks like?

What is the “$” sign in Jquery ?

WhenshouldweuseJquery.noConflict()

What are the different ways by which you can select a HTML element in JQuery ?

What is the use of Document.ready in Jquery ?

Can we have two document.ready in a webpage?

What is JSON?

Do all technologies support JSON?

How can you make a JSON call using Jquery ?

How can we post JSON to Server?

How can we post a complete HTML form in JSON format?

How can we convert JSON string in to c# object?

What are single page applications (SPA)?

What is Angular JS ?

What is the need of ng-model, ng-expression and ng-app in Angular?

How is the data binding in Angular?

What is Jquery ?

Jquery is a reusable javascript library which simplifies javascript coding. So rather than writing length javascript code as below.

Collapse | Copy Code
document.getElementById("txt1").value = "hello";

By jquery the above javascript code is now simplified as below.

Collapse | Copy Code
$("#txt1").val("Hello");

If you want to kick start with Jquery start with the below video which is created by www.questpond.com

So will jquery replace javascript ?

No, Jquery is not meant to replace javascript. Jquery is a library while javascript is a language. Jquery sits on the top of javascript to make your development easy.

So how do we use these reusable jquery libraries?

You need to download Jquery.js file from jquery.com and include the same in your web pages. The jquery files are named with version number like “jquery-1.4.1.js” where 1.4.1 is the version of the JS file. So at the top of your web page you need to include the javascript as shown in the below code.

Collapse | Copy Code
<script src="file:///C:/Documents%20and%20Settings/admin/Documents/My%20Web%20Sites/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

What is CDN (Content delivery network)?

In CDN multiple copies of the website is copied on different geographical servers. When users request website content which have CDN enabled depending on their geographical location , content is served from the nearest geographical location server of the user.

So if a user is from India, the Indian CDN server will serve request for Indian users. This leads to faster delivery of data.

For Jquery files which are the popular CDN’s?

There are two popular CDN’s Microsoft and google.

If you want to reference google CDN Jquery files you can use the below script.

Collapse | Copy Code
<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

If you want to use Microsoft CDN you can use the below javascript.

Collapse | Copy Code
<script type="text/javascript"
    src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js">
</script>

How can we reference local Jquery files if CDN fails?

Many times it’s possible that Microsoft and google servers can go down for some time. So in those situations you would like your page to reference jquery files from local server.

So to implement a CDN fallback is a two-step process:-

First reference the CDN jquery. In the below code you can see we have reference Microsoft CDN jquery file.

Collapse | Copy Code
http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js "></script>

Now if Microsoft CDN is down then the Jquery value will be “undefined”. So you can see in the below code we are checking if the Jquery is having “undefined” value then do a document write and reference your local Jquery files.

Collapse | Copy Code
if (typeof jQuery == 'undefined')
{
  document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}

Below is the full code for the same.

Collapse | Copy Code
<script type="text/javascript" src="file:///C:/Documents%20and%20Settings/admin/Documents/My%20Web%20Sites/%20http:/ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js%2520"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined')
{
  document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>

What is the difference between Jquery.js and Jquery.min.js file?

First thing both the files provide the same jquery functionalities. One is a long version and the other is compressed / minified version. The minified version is compressed to save bandwidth and space by compressing and removing all the white spaces.

Below is the view of Jquery.js.

Below this is view of Jquery.min.js file (compressed and minified).

When should we use jquery.js over jquery.min.js ?

When you are doing development use “jquery.js” file because you would like to debug, see the javascript code etc. Use “Jquery.min.js” for production environment. In production / live environment we would like to consume less bandwidth, we would like to our pages to load faster.

What is the use jquery.vsdoc.js ?

This file you can include if you want to enable intellisense in visual studio for Jquery.

How does the basic syntax of Jquery looks like?

Jquery syntax structure can be broken down in to four parts:-

  • All Jquery commands start with a “$” sign.
  • Followed by the selection of the HTML element. For example below is a simple image where we are selecting a HTML textbox by id “txt1”.
  • Then followed by the DOT (.) separator. This operator will separate the element and the action on the element.
  • Finally what action you want to perform on the HTML element. For instance in the below Jquery code we are setting the text value to “Hello JQuery’.

What is the “$” sign in Jquery ?

The “$” sign is an alias for jquery.

When should we use Jquery.noConflict()?

There are many javascript frameworks like MooTools, Backbone, Sammy, Cappuccino, Knockout etc. Some of these frameworks also use “$” sign so this can lead to conflict with Jquery framework.

So you can use the “noConflict” method and release the jquery “$” sign as shown in the below code.

Collapse | Copy Code
$.noConflict();
jQuery("p").text("I am jquery and I am working&hellip;");

You can also create your own jquery shortcut as shown below.

Collapse | Copy Code
var jq = $.noConflict();
jq("p").text("I am invoked using jquery shortcut&hellip;");

What are the different ways by which you can select a HTML element in JQuery ?

You can select Jquery elements in the following ways:-

Select all

Below is a simple code snippet which selects all paragraph tags and hides them.

Collapse | Copy Code
$("p").hide();

Select by ID

Collapse | Copy Code
$("#Text1").val("Shiv");

Select using Equal method

Select using Find method

Select using Filter method

What is the use of Document.ready in Jquery ?

“Document.Ready” event occurs once the complete HTML DOM is loaded. So the next question is when do we actually need this event?. Consider the below simple code where we are trying to set a text box “text1” with value “Sometext”.

Now at the point when Jquery code tries set the textbox value , at that moment that text box is not available in the HTML DOM. So it throws an exception for the same.

Collapse | Copy Code
<script>
      $("#text1").val("Sometext"); // Throws exception as the textbox is not //accessible at this moment
</script>
</head>
<body>
<input type="text" id="text1" />
</body>

So we would like to execute the Jquery code which sets the textbox value only when all the HTML objects are loaded in DOM. So you can replace the code of setting text box value to something as shown below.

Collapse | Copy Code
<script>
       $(document).ready(function(){
           $("#text1").val("Sometext");
       });
</script>

Here is a nice detail article with a video which explains Jquery Ready event in a more detail manner http://www.dotnetinterviewquestions.in/article_jquery-interview-questions:-when-do-we-need-documentreadyevent-_230.html 

 

Can we have two document.ready in a webpage?

Yes.

How can we attach a method to a HTML element event using Jquery ?

Below is a simple code which attaches a function to click event of a button.

Collapse | Copy Code
$("button").click(function(){
$("p").toggle();
});

Below is one more example where we have attached the a function to a mouse enter event of a paragraph.

Collapse | Copy Code
$("#p1").mouseenter(function(){
  alert("You entered p1!");
});

How can we add a style using Jquery?

$(“li”).filter(“.middle”).addClass(“selected”);

Collapse | Copy Code
<style>
      .selected { color:red; }
</style>

What is JSON?

JSON (JavaScript object notation) helps us to present and exchange data in a self-descriptive, independent and light way. This data can then be easily consumed and transformed in to javascript objects.

Below is a simple example of JSON format looks. You can understand from the format how lightweight and easy the format looks.

Figure :- JSON

The biggest advantage of JSON format is it can be evaluated to a javascript object. For instance you can see in the below code snippet we have a JSON format data which has “name”,”street”,”age” and “phone”. Now this data can be consumed as shown in the code snippet below, evaluated to a javascript object and invoked as anobject property.

You can see how we have called the “name” property using an object “JSONObject.name”.

Collapse | Copy Code
<script type="text/javascript">

var JSONObject= {
"name":"John Johnson",
"street":"Oslo West 555", 
"age":33,
"phone":"555 1234567"};

alert(JSONObject.name); 
</script>

Was not SOAP meant to do the same thing which JSON does?

SOAP is heavy due to XML tags. For example a SOAP message “Shiv” will become short , sweet and light in JSON like “Name” : “Shiv”. Second most important it evaluates as javascript object. To convert the complicated SOAP XML in to javascript JSON object would be a tough and tedious task.

Figure 11.11:- SOAP meant to do the same thing

Do all technologies support JSON?

Yes , Almost all technologies who deal with exchange of data support JSON. For instance if you want to that your WCF service should send JSON message rather than SOAP you can set the “ResponseFormat” as “WebMessageFormat.Json” on your operation contract.

Collapse | Copy Code
[OperationContract]
[WebInvoke(Method="GET", UriTemplate="/GetData", RequestFormat=WebMessageFormat.Json,
           ResponseFormat=WebMessageFormat.Json)]
string GetData();

If you want your MVC to emit out JSON data you can return “JsonResult” as shown below. If you call the below action it will emit out Customer objects in Json format.

Collapse | Copy Code
public JsonResult  CustomerJson()
{
     List<Customer> obj1 = new List<Customer>();
     Thread.Sleep(5000);
            Customer obj = new Customer();
            obj.CustomerCode = "1001";
            obj1.Add(obj);
            return Json(obj1,JsonRequestBehavior.AllowGet);
}

If you want to emit JSON using ASP.NET we need to use the “DataContractJsonSerializer” class as shown in the below code.”myPerson” is the class.

Collapse | Copy Code
DataContractJsonSerializer serializer = new DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, myPerson);
string json = System.Text.Encoding.UTF8.GetString(ms.ToArray());
Response.Clear();
Response.ContentType = "application/json;charset=utf-8";
Response.Write(json);
Response.End();

How can you make a JSON call using Jquery ?

Let’s assume you have a MVC controller action “getEmployee” which emits out employee JSON object as shown in the below code. Please note you can always emit JSON from any server technology like WCF , ASP.NET , MVC etc as discussed in the previous questions.

Collapse | Copy Code
public JsonResult  getEmployee()
{
Emp obj = new Emp();
obj.empcode = "1001";
return Json(obj,JsonRequestBehavior.AllowGet);
}

To make a call to the above MVC action using Jquery we need to use “getJSON” method. Below is the simple code for the same. It has three parameters:-

  1. The first parameter is the URL which emits out JSON. For instance in the below code the URL is “/Employee/getEmployee”.
  2. The next parameter helps us to pass data to the resource which emits out JSON currently it’s the MVC action. Currently we are only doing a get so the second parameter is NULL for now.
  3. The last parameter is the call back function which will be invoked once the MVC action returns data. You can see how the “getData” function just displays the “empcode” property. Because the output is in JSON it automatically converts the JSON data to javascript object.
Collapse | Copy Code
$.getJSON("/Employee/getEmployee", null, getData);
function getData(data)
{
alert(data.empcode);
}

How can we post JSON to Server?

We can use the “post” method of jquery to send data to the server. Below is how the post method call looks like. First parameter is the URL which will accept JSON data, second is the data which we want to send and the final parameter is the call back function where we receive the response.

Collapse | Copy Code
var mydata ={name:"Shiv",city:"Mumbai"};

$.post("/Send/Request", // URL
mydata , // Data to be sent
function(data,status){alert(data + &ldquo; &ldquo; + status);}); // Call back function

How can we post a complete HTML form in JSON format?

To post a complete HTML form we need to call “serialize” function as shown in the below code. “form1” is a HTML form. The data given by the function can then be passed to the “post” method of Jquery.”DisplayData” is a callback function to handle the output given by the server.

Collapse | Copy Code
var Mydata = $("#form1").serialize();
$.post("/Customer/getCustomer",JSON. stringify (MyData), DisplayData);

The above posted JSON string is received at the server side “request.inputstream” , below is a simple sample code for the same.

Collapse | Copy Code
System.IO.Stream body = Request.InputStream;
System.IO.StreamReader reader = new System.IO.StreamReader(body);
string s =   reader.ReadToEnd() ;

How can we convert JSON string in to c# object?

To convert a JSON string to a c# object we need to use the “JavascriptSerializer” class as shown in the below code.

“JsonString” is the string which has the JSON value and by using “Deserialize” we are converting the string to a c# object. Now this object which we receive is a collection of “key” and “value” pair which can be browsed and accessed in c#.

Collapse | Copy Code
var jsonser = new JavaScriptSerializer()
var obj = jsonser.Deserialize<dynamic>(JsonString);
foreach (var x in obj)
{
    String strvalue = x[&ldquo;value&rdquo;];
}

What are single page applications (SPA)?

SPA means you web page has the following :-

  • Utilize the browser client power to the maximum by executing the maximum code on the client side by using javascript , HTML and CSS.
  • Rather than loading the complete page necessary HTML fragments or JSON data is loaded as the user demands.
  • Javascript which handles DOM manipulation, binding, Ajax calls are separated in to controllers thus separating views and models.
  • DOM manipulations are replaced by declarative programming.

What is Angular JS ?

Angular JS is JavaScript framework to create SPA applications. It simplifies complex javascript DOM manipulation code by providing declarative tags. This provides a clean separation between DOM manipulation logic and the HTML view.

For example below is a simple Angular code which helps us to display textbox data in the DIV tag when the user types in the textbox.

Collapse | Copy Code
<input type=text ng-model="name">
<div>
Current user's name: {{name}}

Below is a simple video which explain Angular in 5 minutes with an example: –

 

ANGULAR JS Video

What is the need of ng-model, ng-expression and ng-app in Angular?

“ng-model” helps to store data which is typed in the HTML elements while expression helps to display the model data on the page. “ng-app” defines the root element for angular.

Below is a simple angular code which has all the three things: –

  • So whatever is typed in the textbox gets stored in the model.
  • The model is displayed by an expression {{}}.
  • “ng-app” defines the root.
Collapse | Copy Code
<div ng-app>
<input type=text ng-model="name">
Current user's name: {{name}}
</div>

How is the data binding in Angular?

Its two way binding. So whenever you make changes in one entity the other entity also gets updated.

from: http://www.codeproject.com/Articles/778374/JQUERY-JSON-and-Angular-Interview-questions