Category Archives: JS

深度解析JavaScript的this关键字

这篇文章通过简单的术语和一个真实的例子解释了 this 是什么以及为什么说它很有用。

你的 this

我发现,很多教程在解释 JavaScript 的 this 时,通常会假设你拥有 Java、C++ 或 Python 等面向对象编程语言的背景。这篇文章主要面向那些对 this 没有先入之见的人。我将尝试解释什么是 this 以及为什么它很有用。

或许你迟迟不肯深入探究 this,因为它看起来很奇怪,让你心生畏惧。你之所以使用它,有可能仅仅是因为 StackOverflow 说你需要在 React 用它来完成一些事情。

在我们深入了解它的真正含义以及为什么要使用它之前,我们首先需要了解函数式编程和面向对象编程之间的区别。

函数式编程与面向对象编程

你可能知道也可能不知道,JavaScript 具有函数和面向对象的构造,你可以选择关注其中一个或两者兼而有之。

在我的 JavaScript 之旅的早期,我一方面拥抱函数式编程,一方面像避免瘟疫一样排斥面向对象编程。我对面向对象关键字 this 不甚了解。其中的一个原因是我不明白它存在的必要性。在我看来,完全可以不依赖 this 就可以完成所有的事情。

在某种程度上,我的看法是对的。

你可能只关注其中一种范式而从来不去了解另外一种,作为一名 JavaScript 开发者,你的局限性就体现在这里。为了说明函数式编程和面向对象编程之间的差别,我将使用一组 Facebook 好友数据作为示例。

假设你正在构建一个用户登录 Facebook 的 Web 应用,在登录后显示一些 Facebook 好友的数据。你需要访问 Facebook 端点来获取好友的数据,可能包含一些信息,例如 firstName、lastName、username、numFriends、friendData、birthday 和 lastTenPosts。

你从(臆造的)Facebook API 获得上面的数据。现在,你需要转换它们,让它们符合项目需要的格式。假设你要为每个用户的朋友显示以下内容:

  • 它们的名字,格式为$ {firstName} $ {lastName}
  • 三篇随机的帖子;
  • 从他们生日起到现在的天数。
函数式方法

如果使用函数式方法,就是将整个数组或数组的每个元素传给一个返回所需操作数据的函数:

你从原始数据开始(来自 Facebook API),为了将它们转换为对你有用的数据,你将数据传给一个函数,这个函数将输出你可以在应用程序中显示给用户的数据。

你也可以通过类似的方式获取三个随机帖子并计算朋友生日至今的天数。

函数式方法就是指接受原始数据,将数据传给一个或多个函数,并输出对你有用的数据。

面向对象方法

对于那些刚接触编程和学习 JavaScript 的人来说,面向对象方法可能会更难掌握。面向对象是指你将每个朋友转换为对象,对象包含了用于生成你所需内容的一切。

你可以创建包含 fullName 属性的对象,以及 getThreeRandomPosts 和 getDaysUntilBirthday 函数。

面向对象方法是为你的数据创建对象,这些对象包含了状态和用于生成对你和你的项目有用的数据的信息。

这与 this 有什么关系?

你可能没有想过会写出类似 initializeFriend 这样的东西,你可能会认为它很有用。你可能还会注意到,它其实并非真正的面向对象。

getThreeRandomPosts 或 getDaysUntilBirthday 方法之所以有用,主要是因为闭包。因为使用了闭包,所以在 initializeFriend 返回之后,它们仍然可以访问 data。

假设你写了另一个方法,叫 greeting。请注意,在 JavaScript 中,方法只是对象的一个属性,这个属性的值是一个函数。我们希望 greeting 可以做这些事情:

这样可以吗?

不行!

新创建对象的所有东西都可以访问 initializeFriend 的变量,但对象本身的属性或方法不行。当然,你可能会问:

难道你不能用 data.firstName 和 data.lastName 来返回 greeting 吗?

当然可以。但如果我们还想在 greeting 中包含朋友生日至今的天数,该怎么办?我们必须以某种方式从 greeting 中调用 getDaysUntilBirthday 方法。

是时候让 this 上场了!

那么,this 是什么

在不同的情况下,this 代表的东西也不一样。默认情况下,this 指向全局对象(在浏览器中,就是 window 对象)。但光知道这点对我们并没有太大帮助,对我来说有用的是 this 的这条规则:

如果 this 被用在一个对象的方法中,并且这个方法在对象的上下文中调用,那么 this 就指向这个对象本身。

你会问:“在对象的上下文中调用……这又是什么意思”?

别担心,稍后我们会解释这个。

因此,如果我们想在 greeting 中调用 getDaysUntilBirthday,可以直接调用 this.getDaysUntilBirthday,因为在这种情况下,this 指向对象本身。

注意:不要在全局作用域或在另一个函数作用域内的常规 ole 函数中使用 this!this 是一个面向对象的构造。因此,它只在对象(或类)的上下文中有意义!

让我们重构 initializeFriend,让它使用 this:

现在,在执行完 intializeFriend 后,这个对象的所有东西都限定在对象本身。我们的方法不再依赖于闭包,它们将使用对象本身包含的信息。

这是 this 的一种使用方式,现在回到之前的问题:为什么说 this 因上下文不同而不同?

有时候,你希望 this 可以指向不一样的东西,比如事件处理程序就是一个很好的例子。假设我们想在用户点击链接时打开朋友的 Facebook 页面。我们可能会在对象中添加一个 onClick 方法:

请注意,我们向对象添加了 username,让 onFriendClick 可以访问它,这样我们就可以在新窗口中打开朋友的 Facebook 页面。现在编写 HTML:

然后是 JavaScript:

在上面的代码中,我们为 Bob Ross 创建了一个对象。我们获得与 Bob Ross 相关的 DOM 元素。现在我们想要调用 onFriendClick 方法来打开 Bob 的 Facebook 页面。应该没问题吧?

不行!

什么地方出了问题?

请注意,我们为 onclick 处理程序选择的函数是 bobRossObj.onFriendClick。看到问题所在了吗?如果我们像这样重写它:

现在你看到问题所在了吗?当我们将 onclick 处理程序指定为 bobRossObj.onFriendClick 时,我们实际上是将 bobRossObj.onFriendClick 的函数作为参数传给了处理程序。它不再“属于”bobRossObj,也就是说 this 不再指向 bobRossObj。这个时候 this 实际上指向的是全局对象,所以 this.username 是 undefined 的。

是时候让 bind 上场了!

显式绑定 this

我们需要做的是将 this 显式绑定到 bobRossObj。我们可以使用 bind 来实现:

之前,this 是基于默认规则设置的。通过使用 bind,我们在 bobRossObj.onFriendClick 中将 this 的值显式设置为对象本身,也就是 bobRossObj。

到目前为止,我们已经知道为什么 this 很有用以及为什么有时候需要显式绑定 this。接下来我们要讨论的最后一个主题是箭头函数。

箭头函数

你可能已经注意到,箭头函数像是一个时髦的新事物。人们似乎很喜欢它们,因为它们简洁而优雅。你可能已经知道它们与一般函数略有不同,但不一定非常清楚这些区别究竟是什么。

或许箭头函数的不同之处在于:

在箭头函数内部,无论 this 处于什么位置,它指的都是相同的东西。

让我们用 initializeFriend 示例解释一下。假设我们想在 greeting 中添加一个辅助函数:

这样可以吗?如果不行,要怎样修改才行?

这样当然是不行的。因为 getLastPost 不是在对象的上下文中调用的,所以 getLastPost 中的 this 会回退到默认规则,即指向全局对象。

“在对象的上下文中调用”可能是一个比较含糊的概念。要确定一个函数是否是在“对象的上下文中”被调用,最好的办法是看一下函数是如何被调用的,以及是否有对象“附加”在函数上。

让我们来看看执行 bobRossObj.onFriendClick() 时会发生什么:“找到 bobRossObj 对象的 onFriendClick 属性,调用分配给这个属性的函数”。

再让我们来看看执行 getLastPost() 时会发生什么:”调用一个叫作 getLastPost 的函数”。有没有注意到,这里并没有提及任何对象?

现在来测试一下。假设有一个叫作 functionCaller 的函数,它所做的事情就是调用其他函数:

如果我们这样做会怎样:functionCaller(bobRossObj.onFriendClick)?可不可以说 onFriendClick 是“在对象的上下文中”被调用的?this.username 的定义存在吗?

让我们来看一下:“找到 bobRossObj 对象的 onFriendClick 属性。找到这个属性的值(恰好是一个函数),将它传给 functionCaller,并命名为 fn。现在,执行名为 fn 的函数”。请注意,函数在被调用之前已经从 bobRossObj 对象中“分离”,因此不是“在对象 bobRossObj 的上下文中”调用,所以 this.username 是 undefined 的。

让箭头函数来救场:

箭头函数是在 greeting 中声明的。我们知道,当我们在 greeting 中使用 this 时,它指向对象本身。因此,箭头函数中的 this 指向的对象就是我们想要的。

英文原文:

https://medium.freecodecamp.org/a-deep-dive-into-this-in-javascript-why-its-critical-to-writing-good-code-7dca7eb489e7

Overview of ECMAScript 6 features

Introduction

ECMAScript 6, also known as ECMAScript 2015, is the latest version of the ECMAScript standard. ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is underway now.

See the ES6 standard for full specification of the ECMAScript 6 language.

ES6 includes the following new features:

ECMAScript 6 Features

Arrows

Arrows are a function shorthand using the => syntax. They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript. They support both statement block bodies as well as expression bodies which return the value of the expression. Unlike functions, arrows share the same lexical this as their surrounding code.

More info: MDN Arrow Functions

Classes

ES6 classes are a simple sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.

More info: MDN Classes

Enhanced Object Literals

Object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.

More info: MDN Grammar and types: Object literals

Template Strings

Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.

More info: MDN Template Strings

Destructuring

Destructuring allows binding using pattern matching, with support for matching arrays and objects. Destructuring is fail-soft, similar to standard object lookup foo["bar"], producing undefined values when not found.

More info: MDN Destructuring assignment

Default + Rest + Spread

Callee-evaluated default parameter values. Turn an array into consecutive arguments in a function call. Bind trailing parameters to an array. Rest replaces the need for arguments and addresses common cases more directly.

More MDN info: Default parameters, Rest parameters, Spread Operator

Let + Const

Block-scoped binding constructs. let is the new var. const is single-assignment. Static restrictions prevent use before assignment.

More MDN info: let statement, const statement

Iterators + For..Of

Iterator objects enable custom iteration like CLR IEnumerable or Java Iterable. Generalize for..in to custom iterator-based iteration with for..of. Don’t require realizing an array, enabling lazy design patterns like LINQ.

Iteration is based on these duck-typed interfaces (using TypeScript type syntax for exposition only):

More info: MDN for…of

Generators

Generators simplify iterator-authoring using function* and yield. A function declared as function* returns a Generator instance. Generators are subtypes of iterators which include additional next and throw. These enable values to flow back into the generator, so yield is an expression form which returns a value (or throws).

Note: Can also be used to enable ‘await’-like async programming, see also ES7 await proposal.

The generator interface is (using TypeScript type syntax for exposition only):

More info: MDN Iteration protocols

Unicode

Non-breaking additions to support full Unicode, including new Unicode literal form in strings and new RegExp u mode to handle code points, as well as new APIs to process strings at the 21bit code points level. These additions support building global apps in JavaScript.

// same as ES5.1
"

Modern Web Development

A list of technologies for modern web development.

Introduction

With this article I want to share a compilation of some well known top technologies that can be used today to develop a modern web application. The web development world has changed a lot because of its adaptation to the mobile and social media context, and a lot of new technologies, including servers, databases, development frameworks, and libraries have emerged to help us to  resolve several new problems and challenges.

Background

If you are a project manager, an architect, or a developer, you must choose the appropriate server, database,  language, framework or library for the design and implementation of the entire architecture or for some modules of your modern web application. This article references some of the principal and more used technologies that can help you to achieve this.

Servers

Nginx

Ngin is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. Unlike traditional servers, Nginx doesn’t rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load.

http://wiki.nginx.org/Main

NodeJs  

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

http://nodejs.org 

Databases

MongoDb

MongoDB (from “humongous”) is an open-source  document database, and the leading NoSQL database, designed for ease of development and scaling. Instead of storing data in tables as is done in a “classical” relational database, MongoDB stores structured data as JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster.

http://www.mongodb.org 

Redis

Redis is an open source, BSD licensed, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets. In its outer layer, the Redis data model is a dictionary where keys are mapped to values. One of the main differences between Redis and other structured storage systems is that values are not limited to strings.

http://redis.io 

General purpose Frameworks / Libraries

Backbone.JS

Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

http://backbonejs.org 

Underscore.Js

Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It’s the tie to go along with jQuery’s tux, and Backbone.js’s suspenders.

 http://documentcloud.github.com/underscore 

Sencha frameworks

Sencha creates development frameworks and tools that help you design,  develop, and deploy applications for desktop and mobile devices. Their  goal is to enhance your development experience and final results by  providing well-structured, Web standards-based frameworks and tools that make drafting functional UI and CSS3 animations a breeze, and cloud  services for supporting your application available anytime, anywhere.

http://www.sencha.com/

Zepto.Js

Zepto is a minimalist JavaScript library for modern browsers with a largely jQuery-compatible API. If you use jQuery, you already know how to use Zepto.

http://zeptojs.com

Angular JS

HTML enhanced for web apps! HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web-applications. AngularJS lets you extend HTML vocabulary for your  application. The resulting environment is extraordinarily expressive, readable, and quick to develop.

http://angularjs.org

Bootstrap

Sleek, intuitive, and powerful front-end framework for faster and easier web development. Bootstrap utilizes LESS CSS, is compiled via Node, and is managed through GitHub to help nerds do awesome stuff on the web. Bootstrap was made to not  only look and behave great in the  latest desktop browsers (as well as IE7!), but in tablet and smartphone browsers via responsive CSS as well.

http://twitter.github.io/bootstrap

Specific Libraries

Modernizr

Modernizr is a small JavaScript library that detects the availability of native implementations for next-generation web technologies, i.e. features that stem from the HTML5 and CSS3 specifications. Many of these features are already implemented in at least one major browser (most of them in two or more), and what Modernizr does is, very simply, tell you whether the current browser has this feature natively implemented or  not.

http://modernizr.com

Knockout

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically  (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and  maintainably.

http://knockoutjs.com 

Require.Js

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments,  like Rhino and Node. Using a modular script loader like RequireJS will  improve the speed and quality of your code.

http://requirejs.org 

Amplify Js

AmplifyJS solves the following problems:

  • AJAX Request Management: amplify.request provides a clean and elegant request abstraction for all types of data, even allowing for transformation prior to consumption.
  • Client Side Component Communication : amplify.publish/subscribe provides a clean, performant API for component to component communication.
  • Client Side Browser & Mobile Device Storage : amplify.store takes the  confusion out of HTML5 localStorage. It doesn’t get simpler than using amplify.store(key, data)! It even works flawlessly on mobile devices.
http://amplifyjs.com 

Moment.Js

A 4.8k JavaScript date library for parsing, validating, manipulating, and formatting dates.

http://momentjs.com 

D3 JS

D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful  visualization components and a data-driven approach to DOM manipulation. http://d3js.org 

Breezze 

Breeze is a JavaScript library that helps you manage data in rich client applications. If you store data in a relational database, query and save those data as complex object graphs, and share these graphs across multiple screens of your JavaScript client, Breeze is for you.

http://www.breezejs.com/home 

Mongoose JS

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.  Woks fine with Node JS.

http://mongoosejs.com 

Meta -Languages

CoffeScript   

CoffeeScript is a little language that compiles into JavaScript. Underneath all those awkward braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.

 http://coffeescript.org 

TypeScript

TypeScript is a language for application-scale JavaScript development. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open Source.

http://www.typescriptlang.org

Less

The dynamic stylesheet language. LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions.LESS runs on both the server-side (with Node.js and Rhino) or client-side (modern browsers only).

http://lesscss.org 

Application containers

PhoneGap (Apache Cordova)  

Is an HTML5 app platform that allows you to author native applications with web technologies and get access to APIs and app stores. PhoneGap leverages web technologies developers already know best… HTML and JavaScript.

http://www.phonegap.com 

AppCelerator

Create rich native iOS, Android, hybrid, and mobile web apps from a single JavaScript-based SDK. Titanium empowers you to choose the right way to reach your end users on any device.

http://www.appcelerator.com 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

from:http://www.codeproject.com/Reference/597538/Modern-Web-Development

AngularJS Interview Questions and Answers

Contents

Angular Interview questions and answers

What is AngularJS ?

Explain Directives in Angular?

What are controllers and need of ng-controller and ng-model in Angular?

What are expressions in Angular?

How can we initialize Angular application data?

Explain $scope in Angular?

What is “$rootScope” and how is it related with “$scope”?

Do I need Jquery for Angular?

How is the data binding in Angular ?

How do we make HTTP get and post calls in Angular?

How do we pass data using HTTP POST in Angular ?

What is dependency injection and how does it work in Angular?

How does DI benefit in Angular?

What are services in Angular?

Are Service object instances global or local?

What is a Factory in Angular?

What is the difference between Factory and Service?

My other interview question articles

Angular Interview questions and answers

AngularJS is one of those hot topics which interviewer’s ask for Web programming. In this article we will run through some important Interview questions around AngularJS and how we should be go about answering the same.

Do not forget to see our Learn MVC with Angular in 2 days i.e. ( 16 hours ) video series. Start from this youtube video link. https://www.youtube.com/watch?v=Lp7nSImO5vk

What is AngularJS ?

“AngularJS is a JavaScript framework which simplifies binding JavaScript objects with HTML UI elements.”

Let us try to understand the above definition with simple sample code.

Below is a simple “Customer” function with “CustomerName” property. We have also created an object called as “Cust” which is of “Customer” class type.

Now let us say the above customer object we want to bind to a HTML text box called as “TxtCustomerName”. In other words when we change something in the HTML text box the customer object should get updated and when something is changed internally in the customer object the UI should get updated.

So in order to achieve this communication between UI to object developers end up writing functions as shown below. “UitoObject” function takes data from UI and sets it to the object while the other function “ObjecttoUI” takes data from the object and sets it to UI.

So if we analyze the above code visually it looks something as shown below. Your both functions are nothing but binding code logic which transfers data from UI to object and vice versa.

Now the same above code can be written in Angular as shown below. The javascript class is attached to a HTML parent div tag using “ng-controller” directive and the properties are binded directly to the text box using “ng-model” declarative.

So now whatever you type in the textbox updates the “Customer” object and when the “Customer” object gets updated it also updates the UI.

In short if you now analyze the above code visually you end up with something as shown in the below figure.You have the VIEW which is in HTML, your MODEL objects which are javascript functions and the binding code in Angular.

Now that binding code have different vocabularies.

  • Some developers called it “ViewModel” because it connects the “Model” and the “View” .
  • Some call it “Presenter” because this logic is nothing but presentation logic.
  • Some term it has “Controller” because it controls how the view and the model will communicate.

To avoid this vocabulary confusion Angular team has termed this code as “Whatever”. It’s that “Whatever” code which binds the UI and the Model. That’s why you will hear lot of developers saying Angular implements “MVW” architecture.

Explain Directives in Angular?

Directives are attributes decorated on the HTML elements. All directives start with the word “ng”. As the name says directive it directs Angular what to do.

For example below is a simple “ng-model” directive which tells angular that the HTML textbox “txtCustomerName” has to be binded with the “CustomerName” property.

Some of the most commonly used directives are ng-app,ng-controller and ng-repeat.

What are controllers and need of ng-controller and ng-model in Angular?

“Controllers” are simple javascript function which provides data and logic to HTML UI. As the name says controller they control how data flows from the server to HTML UI.

For example below is simple “Customer” controller which provides data via “CustomerName” and “CustomerCode” property and Add/ Update logic to save the data to database.

Note: – Do not worry too much about the $scope , we will discuss the same in the next question.

“ng-controller” is a directive.Controllers are attached to the HTML UI by using the “ng-controller” directive tag and the properties of the controller are attached by using “ng-model” directive. For example below is a simple HTML UI which is attached to the “Customer” controller via the “ng-controller” directive and the properties are binded using “ng-model” directive.

What are expressions in Angular?

Angular expressionsare unit of code which resolves to value. This code is written inside curly braces “{“.

Below are some examples of angular expressions:-

The below expression adds two constant values.

The below expression multiplies quantity and cost to get the total value.

The below expression displays a controller scoped variable.

The value of Customer code is {{CustomerCode}}

How can we initialize Angular application data?

We can use “ng-init” directive to achieve the same. You can see in the below example we have used “ng-init” directive to initialize the “pi” value.

Explain $scope in Angular?

“$scope” is an object instance of a controller. “$scope” object instance get’s created when “ng-controller” directive is encountered.

For example in the below code snippet we have two controllers “Function1” and “Function2”. In both the controllers we have a “ControllerName” variable.

Now to attach the above controllers to HTML UI we need to use “ng-controller” directive. For instance you can see in the below code snippet how “ng-controller” directive attaches “function1” with “div1” tag and “function2” with “div2” tag.

So this is what happens internally. Once the HTML DOM is created Angular parser starts running on the DOM and following are the sequence of events:-

  • The parser first finds “ng-controller” directive which is pointing to “Function1”. He creates a new instance of “$scope” object and connects to the “div1” UI.
  • The parser then starts moving ahead and encounters one more “ng-controller” directive which is pointing to “Function2”. He creates a new instance of “$scope” object and connects to the “div2” UI.

Now once the instances are created, below is a graphical representation of the same. So the “DIV1” HTML UI is binded with “function1” $scope instance and the “DIV2” HTML UI is binded with “function2” $scope instance. In other words now anything changes in the $scope object the UI will be updated and any change in the UI will update the respective $scope object.

What is “$rootScope” and how is it related with “$scope”?

“$rootScope” is a parent object of all “$scope” angular objects created in a web page.

Let us understand how Angular does the same internally. Below is a simple Angular code which has multiple “DIV” tags and every tag is attached to a controller. So let us understand step by step how angular will parse this and how the “$rootScope” and “$scope” hierarchy is created.

The Browser first loads the above HTML page and creates a DOM (Document object model) and Angular runs over the DOM.Below are the steps how Angular creates the rootscope and scope objects.

  • Step 1:- Angular parser first encounters the “ng-app” directive and creates a “$rootScope” object in memory.
  • Step 2:- Angular parser moves ahead and finds the expression {{SomeValue}}. It creates a variable
  • Step 3:- Parser then finds the first “DIV” tag with “ng-controller” directive which is pointing to “Function1” controller. Looking at the “ng-controller” directive it creates a “$scope” object instance for “Function1” controller. This object it then attaches to “$rootScope” object.
  • Step 4:- Step 3 is then repeated by the parser every time it finds a “ng-controller” directive tag. Step 5 and Step 6 is the repetition of Step 3.

If you want to test the above fundamentals you can run the below sample Angular code. In the below sample code we have created controllers “Function1” and “Function2”. We have two counter variables one at the root scope level and other at the local controller level.

Below is the HTML code for the same. You can we have attached “Function1” and “Function2” two times with “ng-controller” which means four instances will be created.

Above is the output of the code you can see the global variable of root scope has be incremented four times because four instances of $scope have been created inside “$rootScope” object.

Do I need Jquery for Angular?

No , you do not need Jquery for Angular. It’s independent of Jquery.

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.

How do we make HTTP get and post calls in Angular?

To make HTTP calls we need to use the “$http” service of Angular. In order to use the http services you need to make provide the “$http” as a input in your function parameters as shown in the below code.

“$http” service API needs atleast three things:-

  • First what is the kind of call “POST” or “GET”.
  • Second the resource URL on which the action should happen.
  • Third we need to define the “success” function which will be executed once we get the response from the server.

How do we pass data using HTTP POST in Angular ?

You need to pass data using the “data” keyword in the “$http” service API function. In the below code you can see we have created a javascript object “myData” with “CustomerName” property. This object is passed in the “$http” function using HTTP POST method.

What is dependency injection and how does it work in Angular?

Dependency injection is a process where we inject the dependent objects rather than consumer creating the objects. DI is everywhere in Angular or we can go one step ahead and say Angular cannot work without DI.

For example in the below code “$scope” and “$http” objects are created and injected by the angular framework. The consumer i.e. “CustomerController” does not create these objects himself rather Angular injects these objects.

How does DI benefit in Angular?

There are two big benefits of DI: – Decoupling and Testing.

Let’s first start with Decoupling. Consider your application has a logger functionality which helps to log errors , warning etc in some central place. This central place can be a file, event viewer, database etc.

Now let’s say you have a “Customer” class who wants to use the “Logger” classes. Now which “Logger” class to use depends on configuration.

So the code of “Customer” is something as shown below. So depending on the configuration “Customer” class either creates “FileLogger” or it creates “EventLogger” object.

But with DI our code becomes something as shown below. The “Customer” class says he is not worried from where the “Logger” object comes and which type of “Logger” objects are needed .He just wants to use the “Logger” object.

With this approach when a new “Logger” object gets added the “Customer” class does not have to worry about the new changes because the dependent objects are injected by some other system.
The second benefit of DI is testing. Let’s say you want to test the “Customer” class and you do not have internet connection. So your “$http” object method calls can throw errors. But now you can mock a fake “$http” object and run your customer class offline without errors.The fake object is injected using DI.

What are services in Angular?

Service helps to implement dependency injection. For instance let’s say we have the below “Customer” class who needs “Logger” object. Now “Logger” object can be of “FileLogger” type or “EventLogger” type.

So you can use the “service” method of the application and tie up the “EventLogger” object with the “Logger” input parameter of the “Customer” class.

So when the controller object is created the “EventLogger” object is injected automatically in the controller class.

Are Service object instances global or local?

Angular Services create and inject global instances. For example below is a simple “HitCounter” class which has a “Hit” function and this function increments the variable count internally every time you call hit the button.

This “HitCounter” class object is injected in “MyClass” class as shown in the below code.

Below code advises the Angular framework to inject “HitCounter” class instance in the “MyClass” class. Read the last line of the below code specially which says to inject the inject the “HitCounter” instance.

Now let’s say that the “Controller” “MyClass” is attached to twodiv tag’s as shown in the below figure.

So two instances of “MyClass” will be created. When the first instance of “MyClass” is created a “HitCounter” object instance is created and injected in to “MyClass” first instance.

When the second instance of “MyClass” is created the same “HitCounter” object instance is injected in to second instance of “MyClass”.
Again I repeat the same instance is injected in to the second instance, new instances are not created.

If you execute the above code you will see counter values getting incremented even if you are coming through different controller instances.

What is a Factory in Angular?

“Factory” in real world means a premise where products are manufactured. Let’s take an example of a computer manufacturing firm. Now the company produces different kinds and sizes of computers likelaptops,desktops, tablets etc.

Now the process of manufacturing the computer products are same with slight variation. To manufacture any computer we need processor, RAM and hard disk. But depending on what kind of final case packing is the final product shapes.

That’s what the use of Factory in Angular.

For example see the below code we have a “Customer”, “Phone” and “Address” class.

So now we would create different types of “Customer” object types using the combination of “Address” and “Phones” object.

  • We would like to combine “Customer” with “Address” and create a “Customer” object which has “Address” collection inside it.
  • Or must be we would like to create “Customer” object with “Phone” objects inside it.
  • Or must be “Customer” object with both “Phone” and “Address” objects.

In other words we would like to have different permutation and combination to create different types of “Customer” objects.

So let’s start from bottom. Let’s create two factory function’s one which creates “Address” object and the other which creates “Phone” objects.

Now let’s create a main factory function which uses the above two small factory functions and gives us all the necessary permutation and combination.

In the below factory you can see we have three functions:-

  • “CreateWithAddress” which creates “Customer” with “Address” objects inside it.
  • “CreateWithPhone” which creates “Customer” object with “Phone” objects inside it.
  • “CreateWithPhoneAddress” which creates “Customer” object with aggregated “Phone” and “Address” objects.

Below is a simple “CustomerController” which takes “CustomerFactory” as the input. Depending on “TypeOfCustomer” it creates with “Address” , “Phones” or both of them.

You also need to tell Angular that the “CreateCustomer” method needs to be passed in the input. For that we need to call the “Factory” method and map the “CreateCustomer” method with the input parameter “CustomerFactory” for dependency injection.

So if we consume the “CustomerController” in UI , depending on situation it creates different flavors of “Customer” object. You can in the below code we have three different “DIV” tags and depending on the “TypeofCustomer” we are displaying data.

What is the difference between Factory and Service?

“Factory” and “Service” are different ways of doing DI (Dependency injection) in angular. Please read the previous question to understand what is DI.

So when we define DI using “service” as shown in the code below. This creates a new GLOBAL instance of the “Logger” object and injects it in to the function.

When you define DI using a “factory” it does not create a instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.

Below is a simple image which shows visually how DI process for “Service” is different than “Factory”.

Factory Service
Usage When we want to create different types of objects depending on scenarios. For example depending on scenario we want to create a simple “Customer” object , or “Customer” with “Address” object or “Customer” with “Phone” object. See the previous question for more detailed understanding. When we have utility or shared functions to be injected like Utility , Logger , Error handler etc.
Instance No Instance created. A method pointer is passed. Global and Shared instance is created.

My other interview question articles

jQuery, JSON and Less Interview questions with answers

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

100 important ASP.NET MVC interview questions

http://www.codeproject.com/Articles/556995/ASP-NET-MVC-interview-questions-with-answers

HTML 5 Interview questions with answers

http://www.codeproject.com/Articles/702051/important-HTML-Interview-questions-with-answe

WPF interview questions with answers

http://www.codeproject.com/Articles/744082/WPF-Interview-questions-with-answers

from:http://www.codeproject.com/Articles/891718/AngularJS-Interview-Questions-and-Answers