欢迎访问
讨论版列表 - 编程世界 - 主题数: 83 | 文章数: 87 | 管理员: (无)

编程世界

版面 | 文摘区 | 马克区

文章数: 5 | 分页: << 1 >>
admin
[回复] [修改] [删除] [返回版面] 1  
作者: admin, 讨论版: 编程世界, 发表时间: 2016-05-06 22:05:55 PST
标题: JavaScript knowledge
关键字:

http://www.codeproject.com/Articles/620811/Latest-JavaScript-Interview-Questions-and-Answers

5) What are the types used in JavaScript?
Ans:String, Number, Boolean, Function, Object, Null, Undefined.

7) What is the difference between “==” and “===”?
Ans:
“==” checks equality only,
“===” checks for equality as well as the type.

8) textbox value

var name = document.getElementById('txtFullName').value;
Or in jquery: var name = $("#txtFullName").val();

9) checkbox value
var status = document.getElementById('checkbox1').checked; 

1) How to create arrays in JavaScript?
Ans:There are two ways to create array in JavaScript like other languages:

a) The first way to create array
var names = new Array(); 
names[0] = "Vikas";
names[1] = "Ashish";
names[2] = "Nikhil";

b) This is the second way:
var names = new Array("Vikas", "Ashish", "Nikhil");

15) What is the use of Math Object in JavaScript?
Ans: The math object provides you properties and methods for mathematical constants and functions.

var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
var z = Math.sin(90);    Returns the sine of 90

16) What do you understand by this keyword in JavaScript?
Ans: In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most context that is placed on the stack. The following gives two different results (in the browser, where by-default the window object is the 0-level context):

var obj = { outerWidth : 20 };
 
function say() {
    alert(this.outerWidth);
}
 
say();//will alert window.outerWidth
say.apply(obj);//will alert obj.outerWidth

17) What does "1"+2+4 evaluate to?
Ans: Since 1 is a string, everything is a string, so the result is 124.

18) What does 3+4+"7" evaluate to?
Ans: Since 3 and 4 are integers, this is number arithmetic, since 7 is a string, it is concatenation, so 77 is the result.

19) How do you change the style/class on any element using JavaScript?
Ans:
Code
Hide   Copy Code

document.getElementById(“myText”).style.fontSize = “10";

-or-
Hide   Copy Code

document.getElementById(“myText”).className = “anyclass”;

20) Does JavaScript support foreach loop?
Ans: JavaScript 1.6(ECMAScript 5th Edition) support foreach loop,

See example here http://jsfiddle.net/gpDWk/

21) What looping structures are there in JavaScript?
Ans: for, while, do-while loops

 22) What is an object in JavaScript, give an example?
Ans: An object is just a container for a collection of named values:

// Create the man object
Code
Hide   Copy Code

var man = new Object();
man.name = 'Vikas Ahlawat';
man.living = true;
man.age = 27;

23) How you will add function as a property in a JavaScript object? Give an example.
Ans:
Code
Hide   Copy Code

var man = new Object();
man.name = 'Vikas Ahlawat';
man.living = true;
man.age = 27;
man.getName = function() { return man.name;}
console.log(man.getName()); // Logs 'Vikas Ahlawat'.

24) What is the similarity between the 1st and 2nd statement?
1st:- var myString = new String('male'); // An object.
2nd:- var myStringLiteral = 'male'; // Primitive string value, not an object.
Ans: Both will call String() constructor function
You can confirm it by running the following statement:
Hide   Copy Code

console.log(myString.constructor, myStringLiteral.constructor);

27) What would be the output of the following statements?
var object1 = { same: 'same' };
var object2 = { same: 'same' };
console.log(object1 === object2);

 29) What is this?
Hide   Copy Code

var myArray = [[[]]];

Ans: Three dimensional array

30) Name any two JavaScript functions which are used to convert nonnumeric values into numbers?
Ans:

Number()
parseInt()
parseFloat()

Code
Hide   Copy Code

var n1 = Number(“Hello world!”); //NaN
var n2 = Number(“”);             //0
var n3 = Number(“000010”);       //10
var n4 = Number(true);           //1
var n5 = Number(NaN);            //NaN

31) Does JavaScript Support automatic type conversion, If yes give example.

Ans: Yes! Javascript support automatic type conversion. You should take advantage of it, It is most common way of type conversion used by Javascript developers.

Ex.
Hide   Copy Code

var s = '5';
var a = s*1;
var b = +s;
typeof(s); //"string"
typeof(a); //"number"
typeof(b); //"number"


--

※ 来源: homecox.com  [来自: 72.]


admin
[回复] [修改] [删除] [返回版面] 2  
作者: admin, 讨论版: 编程世界, 发表时间: 2016-05-08 00:23:56 PST
标题: Re: JavaScript knowledge
关键字:

http://career.guru99.com/top-85-javascript-interview-questions/

7. Is it possible to break JavaScript Code into several lines?
Breaking within a string statement can be done by the use of a backslash, ‘’, at the end of the first line

Example:
JavaScript
document.write("This is \a program");


8. Which company developed JavaScript?
Netscape is the software company who developed JavaScript.


9. What are undeclared and undefined variables?
Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.


10. Write the code for adding new elements dynamically?
<html> 
<head> <title>t1</title> 
<script type="text/javascript"> 
function addNode() { var newP = document.createElement("p"); 
var textNode = document.createTextNode(" This is a new text node"); 
newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); } 
</script> </head> 
<body> <p id="firstP">firstP<p> </body> 
</html>
<html> 
<head> <title>t1</title> 
<script type="text/javascript"> 
function addNode() { var newP = document.createElement("p"); 
var textNode = document.createTextNode(" This is a new text node"); 
newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); } 
</script> </head> 
<body> <p id="firstP">firstP<p> </body> 
</html>


11. What are global variables? How are these variable declared and what are the problems associated with using them?

Global variables are those that are available throughout the length of the code, that is, these have no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared.

Example:

// Declare a global globalVariable = “Test”;

The problems that are faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.


13. What is ‘this’ keyword in JavaScript?

‘This’ keyword refers to the object from where it was called.


14. Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer, if any?

Timers are used to execute a piece of code at a set time or also to repeat the code in a given interval of time. This is done by using the functions setTimeout, setInterval and clearInterval.

The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay. The setInterval(function, delay) function is used to repeatedly execute the given function in the mentioned delay and only halts when cancelled. The clearInterval(id) function instructs the timer to stop.

Timers are operated within a single thread, and thus events might queue up, waiting to be executed.


16. What is the difference between ViewState and SessionState?

‘ViewState’ is specific to a page in a session.

‘SessionState’ is specific to user specific data that can be accessed across all pages in the web application.


18. Explain how can you submit a form using JavaScript?

To submit a form using JavaScript use document.form[0].submit();

document.form[0].submit();


20. How can the style/class of an element be changed?

It can be done in the following way:
document.getElementById(“myText”).style.fontSize = “20?;
1
	
document.getElementById(“myText”).style.fontSize = “20?;

or
document.getElementById(“myText”).className = “anyclass”;
1
	
document.getElementById(“myText”).className = “anyclass”;

21. Explain how to read and write a file using JavaScript?

There are two ways to read and write a file using JavaScript

    Using JavaScript extensions
    Using a web page and Active X objects


22. What are all the looping structures in JavaScript?

Following are looping structures in Javascript:

    For
    While
    do-while loops

23. What is called Variable typing in Javascript?

Variable typing is used to assign a number to a variable and the same variable can be assigned to a string.

Example	
i = 10;
i = "string";

This is called variable typing.


24. How can you convert the string of any base to integer in JavaScript?

The parseInt() function is used to convert numbers between different bases. parseInt() takes the string to be converted as its first parameter, and the second parameter is the base of the given string.

In order to convert 4F (of base 16) to integer, the code used will be –
JavaScript
parseInt ("4F", 16);


27. Explain how to detect the operating system on the client machine?

In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used.

28. What do mean by NULL in Javascript?

The NULL value is used to represent no value or no object.  It implies no object or null string, no valid boolean value, no number and no array object.


29. What is the function of delete operator?

The functionality of delete operator is used to delete all variables and objects in a program but it cannot delete variables declared with VAR keyword.


30. What is an undefined value in JavaScript?

Undefined value means the

    Variable used in the code doesn’t exist
    Variable is not assigned to any value
    Property doesn’t exist

31. What are all the types of Pop up boxes available in JavaScript?

    Alert
    Confirm and
    Prompt


32. What is the use of Void(0)?

Void(0) is used to prevent the page from refreshing and parameter “zero” is passed while calling.

Void(0) is used to call another method without refreshing the page.

33. How can a page be forced to load another page in JavaScript?

The following code has to be inserted to achieve the desired effect:	
<script language="JavaScript" type="text/javascript" >
<!-- location.href="http://newhost/newpath/newfile.html"; //--></script>

34. What is the data type of variables of in JavaScript?

All variables in the JavaScript are object data types.


38. Explain what is pop()method in JavaScript?

The pop() method is similar as the shift() method but the difference is that the Shift method works at the start of the array.  Also the pop() method take the last element off of the given array and returns it. The array on which is called is then altered.
Example:
var cloths = [“Shirt”, “Pant”, “TShirt”];
cloths.pop();
//Now cloth becomes Shirt,Pant

39. Whether JavaScript has concept level scope?

No. JavaScript does not have concept level scope. The variable declared inside the function has scope inside the function.


40. Mention what is the disadvantage of using innerHTML in JavaScript?

If you use innerHTML in JavaScript the disadvantage is

    Content is replaced everywhere
    We cannot use like “appending to innerHTML”
    Even if you use +=like “innerHTML = innerHTML + ‘html’” still the old content is replaced by html
    The entire innerHTML content is re-parsed and build into elements, therefore its much slower
    The innerHTML does not provide validation and therefore we can potentially insert valid and broken HTML in the document and break it


42. What are the two basic groups of dataypes in JavaScript?

They are as –

    Primitive
    Reference types.

Primitive types are number and Boolean data types. Reference types are more complex types like strings and dates.

43. How generic objects can be created?

Generic objects can be created as:
JavaScript
var I = new object();


45. Which keywords are used to handle exceptions?

Try… Catch—finally is used to handle exceptions in the JavaScript


50. What are the different types of errors in JavaScript?

There are three types of errors:

    Load time errors: Errors which come up when loading a web page like improper syntax errors are known as Load time errors and it generates the errors dynamically.
    Run time errors: Errors that come due to misuse of the command inside the HTML language.
    Logical Errors: These are the errors that occur due to the bad logic performed on a function which is having different operation.

51. What is the use of Push method in JavaScript?

The push method is used to add or append one or more elements to the end of an Array. Using this method, we can append multiple elements by passing multiple arguments

52. What is unshift method in JavaScript?

Unshift method is like push method which works at the beginning of the array.  This method is used to prepend one or more elements to the beginning of the array.


54. How are object properties assigned?

Properties are assigned to objects in the following way –
obj["class"] = 12;

or
obj.class = 12;


55. What is the ‘Strict’ mode in JavaScript and how can it be enabled?

Strict Mode adds certain compulsions to JavaScript. Under the strict mode, JavaScript shows errors for a piece of codes, which did not show an error before, but might be problematic and potentially unsafe. Strict mode also solves some mistakes that hamper the JavaScript engines to work efficiently.

Strict mode can be enabled by adding the string literal “use strict” above the file. This can be illustrated by the given example:

function myfunction() 
{ 
“use strict";
var v = “This is a strict mode function";
}


56. What is the way to get the status of a CheckBox?

The status can be acquired as follows –

alert(document.getElementById(‘checkbox1’).checked);

If the CheckBox will be checked, this alert will return TRUE.


58. Explain window.onload and onDocumentReady?

The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed.

onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.


59. How will you explain closures in JavaScript? When are they used?

Closure is a locally declared variable related to a function which stays in memory when the function has returned.


60. How can a value be appended to an array?

A value can be appended to an array in the given manner –

arr[arr.length] = value;

61. Explain the for-in loop?

The for-in loop is used to loop through the properties of an object.

The syntax for the for-in loop is –
for (variable name in object){

statement or block to execute

}

In each repetition, one property from the object is associated to the variable name, and the loop is continued till all the properties of the object are depleted.


62. Describe the properties of an anonymous function in JavaScript?

A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration.

Anonymous function declaration –
JavaScript
var anon = function() {

alert('I am anonymous');

};

anon();


63. What is the difference between .call() and .apply()?

The function .call() and .apply() are very similar in their usage except a little difference. .call() is used when the number of the function’s arguments are known to the programmer, as they have to be mentioned as arguments in the call statement. On the other hand, .apply() is used when the number is not known. The function .apply() expects the argument to be an array.

The basic difference between .call() and .apply() is in the way arguments are passed to the function. Their usage can be illustrated by the given example.

var someObject = {
 
myProperty : 'Foo',
 
myMethod : function(prefix, postfix) {
 
alert(prefix + this.myProperty + postfix);
 
}
 
};
 
someObject.myMethod('<', '>'); // alerts '<Foo>'
 
var someOtherObject  = {
 
myProperty : 'Bar'
 
};
 
someObject.myMethod.call(someOtherObject, '<', '>'); // alerts '<Bar>'
 
someObject.myMethod.apply(someOtherObject, ['<', '>']); // alerts '<Bar>'


64. Define event bubbling?

JavaScript allows DOM elements to be nested inside each other. In such a case, if the handler of the child is clicked, the handler of parent will also work as if it were clicked too.


69. Write the point of difference between web-garden and a web-farm?

Both web-garden and web-farm are web hosting systems. The only difference is that web-garden is a setup that includes many processors in a single server while web-farm is a larger setup that uses more than one server.


71. What is the method for reading and writing a file in JavaScript?

This can be done by Using JavaScript extensions (runs from JavaScript Editor), example for opening of a file –
JavaScript
fh = fopen(getScriptPath(), 0);


75. What are the various functional components in JavaScript?

The different functional components in JavaScript are-

First-class functions: Functions in JavaScript are utilized as first class objects. This usually means that these functions can be passed as arguments to other functions, returned as values from other functions, assigned to variables or can also be stored in data structures.

Nested functions: The functions, which are defined inside other functions, are called Nested functions. They are called ‘everytime’ the main function is invoked.


77. What are Screen objects?

Screen objects are used to read the information from the client’s screen. The properties of screen objects are –

    AvalHeight: Gives the height of client’s screen
    AvailWidth: Gives the width of client’s screen.
    ColorDepth: Gives the bit depth of images on the client’s screen
    Height: Gives the total height of the client’s screen, including the taskbar
    Width: Gives the total width of the client’s screen, including the taskbar


79. Define unescape() and escape() functions?

The escape () function is responsible for coding a string so as to make the transfer of the information from one computer to the other, across a network.

For Example:
<script>
document.write(escape(“Hello? How are you!”));
</script>

Output: Hello%3F%20How%20are%20you%21

The unescape() function is very important as it decodes the coded string.

It works in the following way. For example:
<script>
document.write(unescape(“Hello%3F%20How%20are%20you%21”));
</script>

Output: Hello? How are you!


80. What are the decodeURI() and encodeURI()?

EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is used to convert the encoded URL back to normal.
<script>
var uri="my test.asp?name=ståle&car=saab";
document.write(encodeURI(uri)+ "<br>");
document.write(decodeURI(uri));
</script>

Output –

my%20test.asp?name=st%C3%A5le&car=saab

my test.asp?name=ståle&car=saab


81. Why it is not advised to use innerHTML in JavaScript?

innerHTML content is refreshed every time and thus is slower. There is no scope for validation in innerHTML and, therefore, it is easier to insert rouge code in the document and, thus, make the web page unstable.

82. What does the following statement declares?
var myArray = [[[]]];
It declares a three dimensional array.


83. How are JavaScript and ECMA Script related?

ECMA Script are like rules and guideline while Javascript is a scripting language used for web development.

84. What is namespacing in JavaScript and how is it used?

Namespacing is used for grouping the desired functions, variables etc. under a unique name. It is a name that has been attached to the desired functions, objects and properties. This improves modularity in the coding and enables code reuse.


85. How can JavaScript codes be hidden from old browsers that don’t support JavaScript?

For hiding JavaScript codes from old browsers:

Add “<!–” without the quotes in the code just after the <script> tag.

Add “//–>” without the quotes in the code just before the <script> tag.

Old browsers will now treat this JavaScript code as a long HTML comment. While, a browser that supports JavaScript, will take the “<!–” and “//–>” as one-line comments.


--

※ 来源: homecox.com  [来自: 72.]


admin
[回复] [修改] [删除] [返回版面] 3  
作者: admin, 讨论版: 编程世界, 发表时间: 2016-05-08 00:24:32 PST
标题: Re: JavaScript knowledge
关键字:

http://dev.fyicenter.com/Interview-Questions/JavaScript/


 34. What are the problems associated with using JavaScript, and are there JavaScript techniques that you discourage?

Browser version incompatibility is the biggest problem. It requires knowing how each scriptable browser version implements its object model. You see, the incompatibility rarely has to do with the core JavaScript language (although there have been improvements to the language over time); the bulk of incompatibility issues have to do with the object models that each browser version implements. For example, scripters who started out with Navigator 3 implemented the image rollover because it looked cool. But they were dismayed to find out that the image object wasn't scriptable in Internet Explorer 3 or Navigator 2. While there are easy workarounds to make this feature work on newer browsers without disturbing older ones, it was a painful learning experience for many.
The second biggest can of worms is scripting connections between multiple windows. A lot of scripters like to have little windows pop up with navigation bars or some such gizmos. But the object models, especially in the older browser versions, don't make it easy to work with these windows the minute you put a user in front of them--users who can manually close windows or change their stacking order. More recently, a glitch in some uninstall routines for Windows 95 applications can disturb vital parts of the system Registry that Internet Explorer 4 requires for managing multiple windows. A scripter can't work around this problem, because it's not possible to detect the problem in a user's machine. I tend to avoid multiple windows that interact with each other. I think a lot of inexperienced Web surfers can also get confused by them. 


 45. What is a prompt box?

A prompt box allows the user to enter input by providing a text box. 


 47. Taking a developer’s perspective, do you think that that JavaScript is easy to learn and use?

One of the reasons JavaScript has the word "script" in it is that as a programming language, the vocabulary of the core language is compact compared to full-fledged programming languages. If you already program in Java or C, you actually have to unlearn some concepts that had been beaten into you. For example, JavaScript is a loosely typed language, which means that a variable doesn't care if it's holding a string, a number, or a reference to an object; the same variable can even change what type of data it holds while a script runs.
The other part of JavaScript implementation in browsers that makes it easier to learn is that most of the objects you script are pre-defined for the author, and they largely represent physical things you can see on a page: a text box, an image, and so on. It's easier to say, "OK, these are the things I'm working with and I'll use scripting to make them do such and such," instead of having to dream up the user interface, conceive of and code objects, and handle the interaction between objects and users. With scripting, you tend to write a _lot_ less code. 


 57. Name the numeric constants representing max,min values

Number.MAX_VALUE
Number.MIN_VALUE 


 58. What does javascript null mean?

The null value is a unique value representing no value or no object.
It implies no object,or null string,no valid boolean value,no number and no array object.


 95. How to convert numbers to strings using JavaScript?

You can prepend the number with an empty string
var mystring = ""+myinteger;
or
var mystring = myinteger.toString();
You can specify a base for the conversion,
var myinteger = 14;
var mystring = myinteger.toString(16);

mystring will be "e". 


 92. How to reload the current page

window.location.reload(true); 


 76. To write messages to the screen without using "document.write()" ?

Changing the contents of an element is a much better solution. When the method showStatus is invoked it will change the content of the span.
...
function showStatus(message) {
var element = document.getElementById("mystatus");
element.textContent = message; //for Firefox
element.innerHTML = message; //for IE (why can't we all just get along?)
return true;
}
...
<span id="mystatus">Test. </span>


 65. To set all checkboxes to true using JavaScript?

//select all input tags
function SelectAll() {
var checkboxes = document.getElementsByTagName("input");
for(i=0;i<checkboxes.length;i++) {
if(checkboxes.item(i).attributes["type"].value == "checkbox") {
checkboxes.item(i).checked = true;
}
}
}


 63. What does the term sticky session mean in a web-farm scenario? Why would you use a sticky session? What is the potential disadvantage of using a sticky session?

Sticky session refers to the feature of many commercial load balancing solutions for web-farms to route the requests for a particular session to the same physical machine that serviced the first request for that session. This is mainly used to ensure that a in-proc session is not lost as a result of requests for a session being routed to different servers. Since requests for a user are always routed to the same machine that first served the request for that session, sticky sessions can cause uneven load distribution across servers. 


 61. What’s a way to append a value to an array?

arr[arr.length] = value;


 96. How to test for bad numbers using JavaScript?

the global method, "isNaN()" can tell if a number has gone bad.
var temperature = parseFloat(myTemperatureWidget.value);
if(!isNaN(temperature)) {
alert("Please enter a valid temperature.");
}


 97. What's Math Constants and Functions using JavaScript?

The Math object contains useful constants such as Math.PI, Math.E
Math also has a zillion helpful functions.
Math.abs(value); //absolute value
Math.max(value1, value2); //find the largest
Math.random() //generate a decimal number between 0 and 1
Math.floor(Math.random()*101) //generate a decimal number between 0 and 100 


 98. What's the Date object using JavaScript?

Time inside a date object is stored as milliseconds since Jan 1, 1970.
new Date(06,01,02) // produces "Fri Feb 02 1906 00:00:00 GMT-0600 (Central Standard Time)"
new Date(06,01,02).toLocaleString() // produces "Friday, February 02, 1906 00:00:00"
new Date(06,01,02) - new Date(06,01,01) // produces "86400000" 


 100. How tp create Arrays using JavaScript??

<script type="text/javascript">
var days = new Array();
days[0] = "Sunday"
days[1] = "Monday"
days[2] = "Tuesday"
days[3] = "Wednesday"
days[4] = "Thursday"
days[5] = "Friday"
days[6] = "Saturday"

document.write("first day is "+days[0])
</script>

This produces

first day is Sunday

A more compact way of creating an array is the literal notation:
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
document.write("first day is "+days[0]) </script>
This produces
first day is Sunday 


 101. How to delete an entry using JavaScript?

The "delete" operator removes an array element, but oddly does not change the size of the array.
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
document.write("Number of days:"+days.length); delete days[4];
document.write("<br />Number of days:"+days.length);
</script>
This produces
Number of days:7
Number of days:7


 102. How to use strings as array indexes using JavaScript?

Javascript does not have a true hashtable object, but through its wierdness, you can use the array as a hashtable.

<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];

for(var i=0; i < days.length; i++) {
days[days[i]] = days[i];
}

document.write("days[\"Monday\"]:"+days["Monday"]);
</script>
This produces
days["Monday"]:Monday


 103. How to use "join()" to create a string from an array using JavaScript?

"join" concatenates the array elements with a specified seperator between them.

<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
document.write("days:"+days.join(","));
</script>
This produces
days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday


 104. How to make a array as a stack using JavaScript?

The pop() and push() functions turn a harmless array into a stack

<script type="text/javascript">
var numbers = ["one", "two", "three", "four"];
numbers.push("five");
numbers.push("six");
document.write(numbers.pop());
document.write(numbers.pop());
document.write(numbers.pop());
</script>
This produces
sixfivefour


 106. How to create an object using JavaScript?

Objects can be created in many ways. One way is to create the object and add the fields directly.

<script type="text/javascript">
var myMovie = new Object();
myMovie.title = "Aliens";
myMovie.director = "James Cameron";
document.write("movie: title is \""+myMovie.title+"\"");
<
This produces
movie: title is "Aliens"
To create an object you write a method with the name of your object and invoke the method with "new".
<script type="text/javascript">
function movie(title, director) {
this.title = title;
this.director = director;
}
var aliens = new movie("Aliens","Cameron");
document.write("aliens:"+aliens.toString());
</script>
This produces
aliens:[object Object]

You can also use an abbreviated format for creating fields using a ":" to separate the name of the field from its value. This is equivalent to the above code using "this.".
<script type="text/javascript">
function movie(title, director) {
title : title;
director : director;
}
var aliens = new movie("Aliens","Cameron");
document.write("aliens:"+aliens.toString());
</script>
This produces
aliens:[object Object] 


 105. How to shift and unshift using JavaScript?

<script type="text/javascript">
var numbers = ["one", "two", "three", "four"];
numbers.unshift("zero");
document.write(" "+numbers.shift());
document.write(" "+numbers.shift());
document.write(" "+numbers.shift());
</script>
This produces
zero one two
shift, unshift, push, and pop may be used on the same array. Queues are easily implemented using combinations. 


 107. How to associate functions with objects using JavaScript?

Let's now create a custom "toString()" method for our movie object. We can embed the function directly in the object like this.

<script type="text/javascript">
function movie(title, director) {
this.title = title;
this.director = director;
this.toString = function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
}
var narnia = new movie("Narni","Andrew Adamson");
document.write(narnia.toString());
</script>
This produces
title: Narni director: Andrew Adamson

Or we can use a previously defined function and assign it to a variable. Note that the name of the function is not followed by parenthisis, otherwise it would just execute the function and stuff the returned value into the variable.

<script type="text/javascript">
function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
function movie(title, director) {
this.title = title;
this.director = director;
this.toString = movieToString; //assign function to this method pointer
}
var aliens = new movie("Aliens","Cameron");
document.write(aliens.toString());
</script>
This produces
title: Aliens director: Cameron 


 108. eval()?

The eval() method is incredibly powerful allowing you to execute snippets of code during exection.

<script type="text/javascript">
var USA_Texas_Austin = "521,289";
document.write("Population is "+eval("USA_"+"Texas_"+"Austin"));
</script>
This produces
Population is 521,289 


 110. How to create a function using function constructor?

The following example illustrates this
It creates a function called square with argument x and returns x multiplied by itself.
var square = new Function ("x","return x*x");


 111. What's Prototypes for JavaScript?

Objects have "prototypes" from which they may inherit fields and functions.

<script type="text/javascript">
function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
function movie(title, director) {
this.title = title;
this.director = director || "unknown"; //if null assign to "unknown"
this.toString = movieToString; //assign function to this method pointer
}
movie.prototype.isComedy = false; //add a field to the movie's prototype
var officeSpace = new movie("OfficeSpace");
var narnia = new movie("Narni","Andrew Adamson");
document.write(narnia.toString());
document.write("
Narnia a comedy? "+narnia.isComedy);
officeSpace.isComedy = true; //override the default just for this object
document.write("
Office Space a comedy? "+officeSpace.isComedy);
</script>


--

※ 来源: homecox.com  [来自: 72.]


admin
[回复] [修改] [删除] [返回版面] 4  
作者: admin, 讨论版: 编程世界, 发表时间: 2016-05-08 00:25:56 PST
标题: Re: JavaScript knowledge
关键字:

Javascript Interview Questions and Answers - Freshers & Experienced


What are the different actions that are performed using JavaScript?
- JavaScript allows the computer to be more secure by putting the privacy policies and disable the unauthorized access to the files.
- It allows many actions to be performed like, setting the browser's preferences and receiving the request from the servers for the client computer.
- The settings that are used gets saved on the client side on the features like actions buttons, appearance and printing.
- It allows easy launching of an application on the client computer with interactive data to be communicated between the server and the client.
- It allows reading and writing of files or directories on the client or server side.
- It allows easy capturing of the data that is live streamed from the server to the client machine for retransmission.
- It also allows to safe and secure the application from the outside world.
How can JavaScript language be separated from objects?
JavaScript treats and creates the applications for the scripting to make the browser's compatible for use. The language is separated from the objects as it allows the syntax to change the environment. It is a language that keeps the page element in the HTML document. JavaScript allows the elements of the page to remain in sync with the document objects. The language is used to create objects that are connected to page elements and other elements in a language. The separation allows the concept of development and effort to be shared with each factor. The JavaScript language allows dynamic data to be presented using the weakly typed language. It also support any action to be taken to support user interface and graphics.
What is the use of DOM?
DOM is also known as Document Object Model which is used to develop a model with documents or web pages containing objects like elements, links, etc. These objects can be manipulated or certain actions like add, delete or change of an element can be performed using this document object model. Through this change in attributes can be done to get all the list of all the elements in the document. The DOM model responds to API calls that result in documented level of DOM recommendation. It is used to support additional behavior on the web page and use of API give an extensible advantage over other models existing. DOM codes are reused to meet the requirement of the real world and to make all the program interoperable.
What is the importance of <SCRIPT> tag?
- JavaScript is used inside <SCRIPT> tag in HTML document. The tags that are provided the necessary information like alert to the browser for the program to begin interpreting all the text between the tags.
- The <script> tag uses JavaScript interpreter to handle the libraries that are written or the code of the program.
- JavaScript is a case sensitive language and the tags are used to tell the browser that if it is JavaScript enabled to use the text written in between the <Script> and </Script> tags.
- The example is given as :
<HTML>
<HEAD>
<!--
<SCRIPT> // Starting of the scripting language
//Your code here
</SCRIPT> --> // End of the scripting language
</HEAD>
<BODY>
// your code here
</BODY>
</HTML>
Why JavaScript is called as Script for all browsers?
JavaScript is written after <SCRIPT> tag and it is surrounded in between the <!-- your code --> tags, this is also known as comment tag. JavaScript interpreter treats the tag such that it treats all the lines in the comments as script lines. The JavaScript comment starts with // inside the <SCRIPT> tag. The script is contained inside <HTML> tag that contains a comment tag. The browser that is non-compatible with JavaScripts ignore the lines and move on, but compatible browsers always treats it as a script and execute it. The browser treat the written lines between the comment tag as normal lines and just thinking of the comment ignores it. Some browsers just treat the <!-- comment--> as a comment only and ignores whatever is written inside it.
What are the requirements of Web application using JavaScript?
There are lots of application that require certain things when the user uses a JavaScript like:
Data entry validation : This tell that if the field of the form is filled out then during the processing of the server the client side can interact with it.
Serverless CGIs : This describes the processes that are not used with JavaScript but programmed as CGI on server, it gives low performace due to more interaction between the applicatioin and the user.
Dynamic HTML interactivity : It allows dynamic position of the data without using any other scripting language.
CGI prototyping : It allows more reduction of time to access the user interface before implementing the application of the CGI.
What are the different objects used in JavaScripts?
JavaScript uses a hierarchical structure that applies to the objects in a document. There are some objects that show the relationship of one object to another using the language.
Window object :
This is the topmost object in the hierarchy. It represent the content area of browser window that consists of HTML documents. Each frame is also a window that has some actions inside it.
Document object :
This object gets loaded in a window and consists of objects of different kind in the model. It consists of the content that will be written in the script.
Form object :
Form objects are used for more interaction with the users. It represents the form elements inside <FORM>...</FORM> tag.
Why is object naming important to use in JavaScript?
- Object naming is used to create script references to objects while assigning names to every scriptable object in the HTML code. The browsers that are script compatible looks for the optional tags and attributes that enables the assigning of a unique name to each object. The example is :
<form name=”dataEntry” method=get>
<input type=”text” name=”entry”>
<frame src=”info.html” name=”main”>
- The names act as a nametags through which the elements can be easily identified and easily located by the browsers. The references made for each object includes the object hierarchy from the top down. References are used to include names of each object that are coming in the window object. The object naming conventions are easy way to loacte the objects and the linking between them can be done more comfortably.
What are the methods involved in JavaScript?
- Method is an informative that gets performed over an action that is related to the object. Method either performs on some object or affect any part of the the script or a document. Object can have as many number of methods that have associations with other objects. There is a method that is used by the JavaScript statement that includes a reference to an object this is given as :
document.orderForm.submit()
document.orderForm.entry.select()
- These are the functions which perform the dynamic interaction with the user. The first statement execute the element when pressed submit button to send a form to a server. These two statements are related to only the form. The scripts that are invoked will have the write of the document as well and will be written as :
document.write(“Give the version “ + navigator.appVersion)
document.write(“ of <B>” + navigator.appName + “</B>.”)
Explain with an example the use of event handlers in JavaScript.
The events in JavaScript are the actions in a document that result from user activity. The actions are like clicking on a button or typing a character in the form. JavaScript object in a document that receives events of different kinds. To handle the events that are taking place requires an even handler that can handle the execution of the events. Event acts like an added attribute that is entered in object’s HTML. The attribute is consisting of event name, sign like (=), instructions. The following code shows the event handler as :
<HTML>
<BODY>
<FORM>
<INPUT TYPE=”button” VALUE=”Hello” onClick=”window.alert (‘HELLO WORLD’)”>
</FORM>
</BODY>
</HTML>
1 2 3 4

    Next Page →

JavaScript vs. Jscript
Both JavaScript and Jscript are almost similar. Java script was developed by Netscape...
Difference between Client side JavaScript and Server side JavaScript
difference between Client side JavaScript and Server side JavaScript - ...
JavaScript - Where are cookies actually stored on the hard disk?
Where are cookies actually stored on the hard disk? - ...
Post your comment
Discussion Board
Javascript interview questions and answers
Are there any predefined constant provided by the browser with the key code values that can be reused?
Use of global object, named as KeyEvent object, used in firefox browser, providing set of pre-defined constants that reflect the keys, which are used on keyboards. The constant’s name used is: DOM_VK_KEYNAME, with values representing the keydown/keyup key codes for the respective keys. For example, DOM_VK_SHIFT is 16, DOM_VK_ESCAPE is 27.

How can I set up my own JavaScript error handler?
To set up your own JavaScript error handler some optional parameters has to be known. These parameters are as follows:
- Textual description of error
- Address (URL) of page on which error occurred
- Number of line in which error occurred
If you want to invoke the default error handler of the browser, then your function should return (false) or vice versa. Example code:
function handlerFunction(description,page,line)
{ // put error-handling operators here
return true;}
window.onerror=handlerFunction;

How do I use JavaScript to password-protect my Web site?
There are several ways in which you can use JavaScript to password-protect your website. This can be done by setting the password by using the given name or pathname of HTML file on your site. Set the location to value entered in the field. Entry of wrong password will result in “invalid URL” error. If password protect pages requires more security then you can set temporary cookies on the page.

How can I prevent others from reading/stealing my scripts or images?
There are no assertive measures which can be taken to foolproof your scripts and images, but preventive measures can be taken like copyrighting your pages, putting watermark on your images and applying non-technological way to protect your images. Scripts are difficult to protect as they can be accessed through many applications and many programs by using the web browsers.
Rohit Sharma 12-11-2011
JavaScript interview questions and answers
How do I write script-generated content to another window?
You can use the methods winRef.document.writeln() or winRef.document.write() to write the script-generated content to another window. winRef stands for windows reference, it is being returned by window.open() method. Use of winRef.document.close() can be used if you want your script’s output to show up. Example code:
writeConsole('Hello world!');
function writeConsole(content) {
top.consoleRef=window.open('','myconsole', 'width=350,height=250'
+',menubar=0')
top.consoleRef.document.writeln( '<html><head><title>Console</title></head>' +' top.consoleRef.document.close() }

How can I request data from the server without reloading the page in the browser?
JavaScript code which is being present and loaded in client browser, can request for data from the web server using XMLHttpRequest object. XMLHttpRequest.open() method is used to open the connection, not to send the request to web server. But, use of the function XMLHttpRequest.send() sends the request in real time. Example code is given below as:
var oRequest = new XMLHttpRequest();
var sURL = "http://"+ self.location.hostname + "/hello/requested_file.htm";
oRequest.open("GET",sURL,false);
oRequest.setRequestHeader("User-Agent",navigator.userAgent);
oRequest.send(null)
if (oRequest.status==200) alert(oRequest.responseText);
else alert("Error executing XMLHttpRequest call!");

How do I add a JavaScript event handler to an HTML page element?
You can use inline event handlers to add a JavaScript handler to an HTML page element. The disadvantage of this technique is that it allows you to have one handler per element. There are different browsers which allow you to have dynamic handler added to the HTML page element. Example of inline event handler is given below:
<a href="ineh.htm" onlick="alert('Hello!')">Good Morning!</a>
// event handlers added by assignment (usually right after the page loads), e.g.:
document.onclick=clickHandler;
document.onkeydown=keyHandler;

Rohit Sharma 12-11-2011
JavaScript interview questions and answers
How do I retrieve a cookie with a given name using a regular expression?
You can use readCookie() function to read the cookie. It provides sufficient arguments that one can find it, flexible to use. It takes cookieName as a parameter and other statements in the block. Below function uses the cookie function as well as regular expression to show the functionality:
function readCookie(cookieName)
{ var rx = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
var sMatch = (' '+document.cookie).match(rx);
if (cookieName && sMatch) return unescape(sMatch[1]);
return '';
}

What value does prompt() return if the user clicked the Cancel button?
Return value of prompt() function depends on browsers. Most of the browsers return the value as null and some return as empty string (“ “). IE is one of the browser which gives the error of empty string when clicked the cancel button by the user, otherwise all the recent browser return the value as null. The code to check this is as follows:
userInput = prompt('Prompt text','Suggested input');
if (userInput) {
// do something with the input
}

Why does the browser display the slow script warning?
When JavaScript on your browser is running but, it is not responding from a long time, then browser may display a warning message and give the user an option to terminate the script. Example, while loading a video application on Internet Explorer 8.0, it displays Yes/No dialog message like this:
Stop running this script?
A script on this page is causing Internet Explorer to run slowly.
If it continues to run, your computer might become unresponsive.
Rohit Sharma 12-11-2011


--

※ 来源: homecox.com  [来自: 72.]


admin
[回复] [修改] [删除] [返回版面] 5  
作者: admin, 讨论版: 编程世界, 发表时间: 2016-05-08 14:54:20 PST
标题: Re: JavaScript knowledge
关键字:

https://github.com/johnpolacek/Front-end-Developer-Interview-Questions/blob/master/README.md


JOB INTERVIEW QUESTIONNAIRE

@version 1.0
Contributors

@bentruyman (http://bentruyman.com/), @roger_raymond (http://twitter.com/iansym), @ajpiano (http://ajpiano.com/), @paul_irish (http://paulirish.com/), @SlexAxton (http://alexsexton.com/), @boazsender (http://boazsender.com/), @miketaylr (http://miketaylr.com/), @vladikoff (http://vladfilippov.com/), @gf3 (http://gf3.ca/), @jon_neal (http://twitter.com/jon_neal), @wookiehangover (http://wookiehangover.com/) and @darcy_clarke (http://darcyclarke.me)
General Questions:

    Are you on Twitter?
        Yes
        If so, who do you follow on Twitter?
            Mostly web developers and designers.

    Are you on GitHub?
        If so, what are some examples of repos you follow
            HTML5 Boilerplate, Modernizr, Video.js and lots more.

    What blogs do you follow?
        Lots (and also podcasts) including HTML5Weekly, JavaScript Weekly / JavaScript Show, CSS Tricks / Shoptalk, JavaScript Jabber, The Web Ahead And I try to devour as much of what is on Hacker News as possible.

    What version control systems have you used (Git, SVN etc.)?
        Git and SVN

    What is your preferred development environment? (OS, Editor, Browsers, Tools etc.)
        Mac, Sublime 2, Chrome Dev Tools, Firebug, Photoshop, lots of online resources

    Can you describe your workflow when you create a web page?
        Usually start with my HTML5 Boilerplate fork, then markup, then styling, then JavaScript. I try to tackle the most challenging stuff first.

    Can you describe the difference between progressive enhancement and graceful degradation?
        Progressive enhancement is starting from a baseline and then building enhancements for new browser tech on top.
        Graceful degradation is starting with designing the most optimal browser experience, then designing fallbacks for older browsers.
        Some methods for doing this are media queries, javascript polyfills and javascript detection libraries like Modernizr

    Explain what "Semantic HTML" means.
        It means the opposite of using divs for everything. Taking advantage of new HTML5 elements like nav, article, header, footer, etc.

    What browser do you primary develop in and what developer tools do you use?
        Chrome

    How would you optimize a websites assets/resources?
        Use photoshop to compress image files, choosing the best format for the best compression, then use ysmush.it to get even more lossless compression.
        Concatenate and minify JavaScript and CSS Files
        Use sprite sheets and icon fonts
        Use a cdn for jquery and hosting video
        Cache static files (in the past this would be typically done with a php header, but now you could use a HTML5 Cache Manifest)

    Why is it better to serve site assets from multiple domains?
        Parallel downloads speed up the page load. Also, serving static files from a CDN (S3 for example) takes some load off your server.

    How many resources will a browser download from a given domain at a time?
        Depends on the browser. The recommendation is to stick to 2-4 hostnames (source)

    Name 3 ways to decrease page load. (perceived or actual load time)
        The best way is usually to reduce your image sizes. Minify and concatenate JS/CSS. Have JS at the bottom of the page. Use a CDN.

    If you jumped on a project and they used tabs and you used spaces, what would you do?
        Conform to the conventions (stay consistant)

    Write a simple slideshow page
        Already did

    What tools do you use to test your code's performance?
        Yahoo! YSlow
        Google PageSpeed
        Pingdom Tools
        JSPerf
        Dromaeo

    If you could master one technology this year, what would it be?
        I put more importance on building cool things over any specific type of tech. People seem to be doing neat stuff with Node.js + Arduino lately

    Explain the importance of standards and standards bodies.
        Standards are the only thing holding this crazy chaotic thing we call the web together. They make it possible for us to code up web stuff that works cross-browser/platform/device/screen

HTML-Specific Questions:

    What's a doctype do, and how many can you name?
        Defines the version of html the document is using. Let's just do html and call it a day. This ain't 2007.

    What's the difference between standards mode and quirks mode?
        Quirks mode is for old (really old!) browsers. It essentially gives them permission to continue to follow their own busted way of rendering a web page as opposed to standards mode where all the browsers have come to an agreement about how to handle styling and markup. This question feels dated.

    What are the limitations when serving XHTML pages?
        Are there any problems with serving pages as application/xhtml+xml?
        Yes. Here's a nice article on this stuff. These questions are giving me a headache. Let's just do html5.

    How do you serve a page with content in multiple languages?
        You would generally use a CMS for this, which would be wired up with different content for each language, but still output the same structure and styling.

    What kind of things must you be wary of when design or developing for multilingual sites?
        Spacing is a biggie. You want to make sure you have a fluid design that can accommodate different sized type. This can be particularly noticeable in navigation buttons that might overlap content or break in the middle of a word.

    Can you use XHTML syntax in HTML5?
        Yes

    How do you use XML in HTML5?
        I like the idea of HTML as a flavor of XML (XHTML) - i.e. quoted attr's and trailing slashes on br's, img's, etc.

    What are data- attributes good for?
        Storing data in the DOM. I love it.

    What are the content models in HTML4 and are they different in HTML5?
        In HTML4, there are 2 types of elements: Block and Inline. HTML5 emphasizes semantics and structure, so it has organized its elements into the categories of metadata, flow, sectioning, heading, phrasing, interactive & embedded

    Consider HTML5 as an open web platform. What are the building blocks of HTML5?
        HTML, CSS and JavaScript

    Describe the difference between cookies, sessionStorage and localStorage.
        Cookies are for storing small amounts of website data, such as a user name. HTML5 Web Storage is a faster, improved means of storing website data. sessionsStorage is for temporary data, and localStorage is for persistant data.

JS-Specific Questions

    Which JavaScript libraries have you used?
        jQuery of course. Other ones I've used are jQuery UI, jQuery Mobile, Modernizr, Greensock and then lots of little utility ones

    Have you ever looked at the source code of the libraries/frameworks you use?
        Yeah. Plenty of good stuff to learn in there. Such as https://vimeo.com/12529436 and https://vimeo.com/18901514

    How is JavaScript different from Java?
        They are very different. From what I've heard, the only reason they share the name is for marketing purposes. Java is a programming language that gets compiled then run as a standalone 'applet' in a VM or browser. Whereas JavaScript is a scripting language designed to be run only through a browser. They are both OOP, but Java is strictly typed while JS is loose.

    What's a hashtable?
        A hashtable is an associative array of key/value pairs. JavaScript Objects are hashtables.

    What are undefined and undeclared variables?
        undeclared vars have not been declared by a var statement (considered null). undefined vars have been declared but have no value.

    What is a closure, and how/why would you use one?
        Closures provide a means of putting function definitions and expressions inside of other functions. A common use would be binding event handler functions so that 'this' refers to the event object. The Module Pattern is the classic example.

    What's a typical use case for anonymous functions?
        For single use methods, like when you need to pass a one-liner of code to another function. Or when you want to scope vars via a closure.

    Explain the "JavaScript module pattern" and when you'd use it.
        The module pattern is a way of organizing and encapsulating code via a closure. It allows you to create public/private functions and vars inside an object (the module). It lessens the likelihood of naming conflicts and unintended interactions with other functions/vars on the page. Modules should work independently and be easily extensible. Using modules enables to write widgets and plugins that interact with each other.

    How do you organize your code?
        I like using the Module Pattern quite a bit. Whenever possible, I like to widgetize/pluginize my code.

    What's the difference between host objects and native objects?
        Native Objects are objects/methods that exist in the ECMAScript spec (Date, Math, String methods, etc.) Host Objects are created by the environment (window, history, getElementByID, etc.) or ones you create yourself.

    Difference between:

function Person(){} var person = Person() var person = new Person()

* *The first is undefined. The second is an object.*

    What's the difference between .call and .apply?
        .apply and .call do the same thing, but .apply uses an array containing arguments for the target method as the second parameter.

    explain Function.prototype.bind?
        Use this to create functions that when called have a particular value for this and therefore binding it to the original value of the target object

    When do you optimize your code?
        All the time, from the beginning structure, to refactoring along the way, to re-evaluating at the end.

    Can you explain how inheritance works in JavaScript?
        JavaScript does not have classes - it uses prototypal inheritance. There continues to be debate over what specific inheritance pattern works best. I like John Resig’s approach as implemented in $.Class by JavaScriptMVC simply because it just makes the most sense to me.

    When would you use document.write()?
        It is bad practice to use document.write(). Instead, use DOM manipulation methods like innerHTML. The one case where it is acceptable from what I understand is where you would want to add link to a stylesheet if JavaScript is enabled.

    What's the difference between feature detection, feature inference, and using the UA string
        Using feature detection over user agent detection is favored because devices and device features are constantly changing and therefore it is better to design behavior based on whether particular features are present or not. For example, by using Modernizr or yepnope.

    Explain AJAX
        AJAX is used for asynchonously sending and receiving data without interfering with any processes occuring on the page. It is used for things like form submission, loading dynamic content assets and user interaction like chat rooms and multiplayer games. When data is returned from a server, a callback function is then executed that handles the data. AJAX stands for Asynchronous JavaScript and XML, which has become a bit outdated as most are using JSON these days. But, AJAJ just doesn’t have as nice a ring to it though.

    Explain how JSONP works (and how it's not really AJAX)
        JSONP stands for JSON with padding. The padding is a callback function that is used to wrap the data returned from the server. The reason for its existence is to get around browser's same-origin restriction against cross domain requests.

    Have you ever used JavaScript templating? If so, what libraries have you used? (Mustache.js, Handlebars etc.)
        *I've used jQuery Templates and more recently Mustache. Recently though, my favorite has been to use ICanHaz.js with Mustache. *

    Explain "hoisting".
        Hoisting is a feature in JavaScript where var declarations are moved to the top of the function body. However, the initialization/assignment of the var is not. Therefore it is considered best practice to define and assign all var declarations at the top of a function.

    What is FOUC? How do you avoid FOUC?
        FOUC = Flash Of Unstyled Content. The standard way is to do a .no-js hook on the document body that gets changed to .js by some script in the document head.

    Describe event bubbling.
        Events are dispatched first at the event target, then propagate up through the target element's parent and ancestors, 'bubbling' all the way up to the document root.

    What's the difference between an "attribute" and a "property"?
        An attribute carries information about an element in the form of a key value pair. A property is the key portion of that attribute.

    Why is extending built in JavaScript objects not a good idea?
        The main reason not to do it is to avoid conflicts - for example, if two different scripts are extending an object in an incompatible way. If every JS library out there started extending object prototypes, it would create a huge mess. It is best to leave the built-ins alone, as that way everyone knows their expected behavior and there are no surprises down the road.

    Why is extending built ins a good idea?
        The temptation is that by extending a native object, you can quickly bring useful functionality to JS prototypes, like Array or String. But that quick solution can lead to big headaches later on. Are there any good use cases? Some say a worthy use would be making polyfills for older browsers to bring them up to the latest EcmaScript standards, yet even that seems open to causing trouble. Best steer clear. There be dragons.

    Difference between document load event and document ready event?
        Document ready fires when the html load has completed and the DOM is 'ready'. The window load fires when images and other page content have all finished loading.

    What is the difference between == and ===?
        === is strictly equal, while == allows for truthiness, where the objects being compared are equal after type coercion. For example, 1=="1" is true, but 1==="1" is false.

    Explain how you would get a query string parameter from the browser window's URL.
        I would look up how to do it on stackoverflow.

    Explain the same-origin policy with regards to JavaScript.
        A script can read only the properties of windows and documents that are loaded from the same host, through the same port, and by the same protocol as the script itself. ([source])(http://docstore.mik.ua/orelly/webprog/jscript/ch21_03.htm)

    Explain event delegation.
        Event delegation is assigning event handlers further up the DOM tree to capture events as they bubble up from children. For example, adding a click event listener to a <ul> to capture any clicks upon its child <li> elements.

    Describe inheritance patterns in JavaScript.
        Didn't we do this one already?

    Make this work:

[1,2,3,4,5].duplicator(); // [1,2,3,4,5,1,2,3,4,5]

* *Ok, but this is going to extend the built in JS Array Object, which we already said was a bad idea.*

Array.prototype.duplicator = function() {
    return this.concat(this);
}

// I'd prefer to do this:
function duplicateArray(array) {
    return array.concat(array);
}
var dup = duplicateArray([1,2,3,4,5])

// Or this:
function duplicateArray(array, numDups) {
    var dups = [];
    for (var i=0; i<numDups+1; i++) {
        dups = dups.concat(array);
    }
    return dups;
}
var dup = duplicateArray([1,2,3,4,5], 1);

    Describe a strategy for memoization (avoiding calculation repetition) in JavaScript.
        The standard way to do it is to create a memoization function that creates a cache object for calculations. You then pass calculations into the function, which checks if it already exists in the cache. If it does, it returns the result without having to actually perform the calculation. If the calculation doesn't exist in the cache, it performs and returns the calculation, then also stores it in the cache object for next time.

    Why is it called a Ternary statement, what does the word "Ternary" indicate?
        Ternary indicates an inline if statement, comprised of 3 parts. The first is a boolean expression. The second is an expression that is returned if the boolean is true. The third is an expression returned if the boolean is false. “In computer science, a ternary operator is an operator that takes three arguments.” - http://en.wikipedia.org/wiki/Ternary_operation

    What is the arity of a function?
        The number of arguments expected by a function. ([source])(https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/arity)

JS-Code Examples:

~~3.14

Question: What value is returned from the above statement? Answer: 3

"i'm a lasagna hog".split("").reverse().join("");

Question: What value is returned from the above statement? Answer: "goh angasal a m'i"

( window.foo || ( window.foo = "bar" ) );

Question: What is the value of window.foo? Answer: "bar" only if window.foo was falsey otherwise it will retain its value.

var foo = "Hello"; (function() { var bar = " World"; alert(foo + bar); })(); alert(foo + bar);

Question: What is the outcome of the two alerts above? Answer: "Hello World" & ReferenceError: bar is not defined

var foo = [];
foo.push(1);
foo.push(2);

Question: What is the value of foo.length? **Answer: 2

var foo = {};
foo.bar = 'hello';

Question: What is the value of foo.length? **Answer: undefined
jQuery-Specific Questions:

    Explain "chaining".
        jQuery methods return an object, therefore making it possible to run sequential methods on the same jQuery object. This results in shorter, cleaner code that runs faster because it reduces interaction with the DOM.

    Explain "deferreds".
        A jQuery Deferred Object is used to manage callbacks based on success and failure of other functions. It is primarily used for handling ajax requests that require flexible or complex state management. Multiple callbacks can be attached to a single deferred object in a chain, with methods like deferred.then() deferred.done() and deferred.fail(). Callbacks can even be bound after the event dispatch has occured.

    What are some jQuery specific optimizations you can implement?
        Use chaining as much as possible. Optimize selectors (for example using .find() rather than context). Cache selectors that get run more than once. Use .on() assigned to a parent element, rather than binding lots of event listeners to child elements. Reduce the amount of DOM manipulation (for example, if you are building a list, instead of using multiple .append() calls to a <ul> element, instead build all the <li> elements as a string and use .append() just once).

    What does .end() do?
        You use .end() when chaining methods to revert back to a previous selected group of elements. For example, if you do a .find() and then .end(), it reverts the selector back to its state before the .find() was executed. It enables you to do less DOM lookups.

    How, and why, would you namespace a bound event handler?
        You would namespace an event handler if you want to refer to a specific event handler for triggering or removal (for example, you could have multiple click event handlers bound to an element, but only want to remove one of them).

    Name 4 different values you can pass to the jQuery method.
        Selector (string), HTML (string), Callback (function), HTMLElement, object, array, element array, jQuery Object etc.

    What is the effects (or fx) queue?
        It is jQuery’s library for animation.

    What is the difference between .get() and .eq()?
        eq() returns a jQuery object and get() returns a DOM element.

    What is the difference between .bind(), .live(), and .delegate()?
        .bind() was the original method for attaching event listeners in jQuery, and is very straightforward way of putting an event listener onto an element. .live() is an improvement over .bind() in that it gets attached only once to a given selector, as opposed to .bind() which binds individual event listeners to each matched element. .delegate() is even better because you can attach the listener to a root element that will catch events that bubble up from the designated element delegates (resulting in better performance). It also works great for dynamic elements that get added to the page after the original event handler was attached.

    What is the difference between $ and $.fn? Or just what is $.fn.
    Optimize this selector:

$(".foo div#bar:eq(0)")

* *`$('#bar')`*

CSS-Specific Questions:

    Describe what a "reset" CSS file does and how it's useful.
        A CSS reset is used to create a baseline set of styles that will display the same across browsers.

    Describe Floats and how they work.
        Elements can be floated left or right, elements after the float will then wrap around it (unless the clear property is applied to the element).

    What are the various clearing techniques and which is appropriate for what context?
        You could float a series of elements to achieve a gallery, then use clear both to force line breaks. You could make a flexible 2 or 3-column layout, then clear both on the footer. You would use clearfix technique to force a container’s height to adjust to fit floated elements.

    Explain CSS sprites, and how you would implement them on a page or site.
        First, create a spritesheet that contains all the commonly used graphic elements on your website. Then to use the sprites, use the spritesheet as a background image on a <div> set to the size of the sprite, then use background-position to display the appropriate sprite. A newer technique would be to use icon fonts, which have the added advantage of being vector-based and therefore look nicer on higher resolution (retina) screens. Some nice icon fonts are Font Awesome and Foundation Icons

    What are your favourite image replacement techniques and which do you use when?
        Webfonts have replaced many of the use cases for image replacement. However, it still is necessary from time to time, especially for something like a company logo. I like the HTML5 Boilerplate(H5BP) approach of setting the font size to zero rather than use text-indent.

    CSS property hacks, conditionally included .css files, or... something else?
        Once again, I go with H5BP and their technique of conditional classes on <html>

    How do you serve your pages for feature-constrained browsers? What techniques/processes do you use?
        First, its important to take a look at any analytics you can to see what browsers and devices your users are using. Next of course, it depends on the content. I've used various approaches (graceful degradation, progressive enhancement, mobile first). I like the responsive web design approach of primarily using media queries. Also doing feature detection (usually with Modernizr) combined with polyfills.

    What are the different ways to visually hide content (and make it available only for screen readers)?
        Some people have used text-indent or absolute positioning to move the content off the page, but the favorable approach is to use clip: rect(1px, 1px, 1px, 1px); along with some other properties. Again, HTML5 Boilerplate is helpful here, as they have a nice .visually-hidden class for just this purpose.

    Have you ever used a grid system, and if so, what do you prefer?
        I used to use 960.gs (I think like everyone else). With fluid grids being all the rage these days (deservedly so) I've messed around with a few like Golden Grid System and Skeleton - Most of the time, I think I've been using Twitter Bootstrap or rolling my own.

    Have you used or implemented media queries or mobile specific layouts/CSS?
        Only like all the time.

    Any familiarity with styling SVG?
        I have not, but I always say the key to being a good developer is to be good at Google (and these days StackOverflow)

    How do you optimize your webpages for print?
        I would start with the H5BP print stylesheet as a base and then customize as needed.

    What are some of the "gotchas" for writing efficient CSS?
        One mistake I see commonly is using to many linked .css files. The old practice of trying to avoid 'class-itis' is outdated and no longer good practice (instead use semantic class names). The key is to not style 'pages', but rather style 'modules'. Optimize for change. Website maintainability is important.

    Do you use CSS preprocessors? (SASS, Compass, Stylus, LESS)
        I have not used them much other to try them out. If I worked with a team that used them, I would have no problem with doing so.

    How would you implement a web design comp that uses non-standard fonts?
        I would use webfonts via @font-face. I would be very relectant to use any other technique for any significant amount of text.

    Explain how a browser determines what elements match a CSS selector?

        Browsers read CSS from right to left. The less rules the browser has to evaluate, the faster the styling engine will perform.

        To resolve conflicts between rules applying to the same element, browsers follow a set of rules to determine which selector is more specific (CSS Specificity). There is a weighted point system, where element selectors are 1 point, class selectors are 10 points and ID selectors are 100 points. In the case of 2 equally weighted selectors, the last rule is the one that gets followed.

Optional fun Questions:

    What's the coolest thing you've ever coded, what are you most proud of?
        Even though its a bit silly, my Scrollorama and Superscrollorama plugins have gotten a lot of positive response and thats made me proud.

    Do you know the HTML5 gang sign?
        Yes

    Are you now, or have you ever been, on a boat.
        I have ridden on boats of many sizes.

    What are your favorite parts about the developer tools you use?
        Running JS in the console is purty dern cuhl.

    Do you have any pet projects? What kind?
        Yes, yes yes.

    Explain the significance of "cornify".
        Bringing rainbow happiness to the dull corners of the web.

    On a piece of paper, write down the letters A B C D E vertically. Now put these in descending order without writing one line of code.
        Wait and see if they turn the paper upside down

    Pirate or Ninja?
        I think of myself more as Winston Wolf

    If not Web Development, what would you be doing?
        I used to draw stuff, so maybe that.

    Where in the world is Carmen Sandiego?
        Probably hanging out with Nora the Explorer

    What's your favorite feature of Internet Explorer?
        The part where everybody makes funny jokes about it

    Complete this sentence: Brendan Eich and Doug Crockford are the __________ of javascript.
        Eich and Crockford

    jQuery: a great library or the greatest library? Discuss.
        Greatestest


--

※ 来源: homecox.com  [来自: 72.]


Reply

Please log in first.