This series of content for my usual project practice and reference Mdn,msdn, "JavaScript language Essence", "effective JavaScript" and other materials, and organize their daily accumulation of Evernote write, time is too long some code sample source can not be tested. This series does not allow any form of reprint, thank you. From Yeanzhi
Outline first day: JavaScript variables, operators and variable scopes The next day: JavaScript functions The third day: Objects and prototypes fourth day: Talking about functions and inheritance fifth day: Built-in Objects sixth day: Special properties and Techniques first day: JavaScript variable with expression (2) operator
The following are some of the operators in JavaScript
- Assignment operators
- Comparison operators
- Arithmetic operators
- Bitwise operators
- logical operators
- String operators
- Special operators
In this article, we introduce only a few operators that are important or have special techniques, with emphasis on special operators (operators)
logical operators
Logical operators are typically used for Boolean (logical) values, in which case they return a Boolean value. However,&& and | | The operator actually returns a value of the specified operand, so these operators are also used for non-Boolean types, which return a non-boolean value.
Skills:
Use logical AND OR in conditions
var foo = 10; foo == 10 && doSomething(); //等同于if (foo == 10) doSomething(); foo == 5 || doSomething(); //等同于if (foo != 5) doSomething();
Logic or can also be used to set default values, such as default values for function parameters.
arg1 = arg1 || 10;
Special operators
JavaScript has the following special operators:
- Conditional operators
- Comma operator
- Delete
- Inch
- instanceof
- New
- This
- typeof
- void
1, conditional operator (unique three-mesh operator)
Condition? Val1:val2
2, comma operator
The comma operator (,) evaluates the two operands and returns the value of the second operand. It is often used in a for loop to update multiple variables at each iteration. Like what:
for (var i = 0, j = 9; i <= 9; i++, j--) expression
About Looping techniques
var sum = 0; for (var i = 0, len = arrayNumbers.length; i < len; i++) { sum += arrayNumbers[i]; }//还有一种写法for (var i = 0, item; item = a[i++];) { // Do something with item}//这里我们使用了两个变量。//for 循环中间部分的表达式仍然用来判断是否为真—如果为真,那么循环继续。//因为i每次递增 1,这个数组的元素会被逐个传递给 item 变量。//当遇到一个假值元素(如undefined)时,循环结束。
This is not recommended for in, and if someone adds a new attribute to Array.prototype, these properties are also traversed using such loops:
for (var i in a) { // Do something with a[i]}
3,delete
The delete operator deletes an object's properties. It doesn't touch any of the properties in the prototype chain.
Attention:
3.1, in strict mode, if the property is a non-configurable (non-configurable) property, the deletion throws an exception, and false is returned in non-strict mode. All other conditions return true.
The 3.2,delete operator is not related to directly freeing memory (which can be released indirectly only by dereferencing)
3.3, properties of some objects cannot be deleted. These attributes are marked as Dontdelete in the ECMA262 specification
x = 42; // 隐式声明的全局变量var y = 43; // 显式声明的全局变量myobj = new Number();myobj.h = 4; // 添加属性hmyobj.k = 5; // 添加属性kdelete x; // 返回 true (隐式声明的全局变量可以被删除)delete y; // 返回 false (显式声明的全局变量不能被删除,该属性有DontDelete标记)delete Math.PI; // 返回 false (内置对象的内置属性不能被删除, 该属性有DontDelete标记)delete myobj.h; // 返回 true (用户定义的属性可以被删除)with(myobj) { delete k; // 返回 true (相当于delete myobj.k)} delete myobj; // 返回 true (隐式声明的全局变量可以被删除)
3.4, you cannot delete a property that an object inherits from the prototype (although it can be deleted directly from the prototype).
function Foo(){} Foo.prototype.bar = 42; var foo = new Foo(); delete foo.bar; // 无效的操作 alert(foo.bar); // alerts 42, 继承的属性 delete Foo.prototype.bar; // 直接删除原型上的属性 alert(foo.bar); // alerts "undefined",已经没有继承的属性
3.5, deleting array elements
When you delete an array element, the length property of the array does not become smaller. For example, if a[3] is removed, a[4] is still a[4], a[3] becomes undefined.
When you delete an array element with the delete operator, the deleted element is not part of the array at all. In the following example, Name[3] is completely deleted using Delete.
var name = ["ye","an","z","h","i"];delete name[3];console.log(name);//[ 'ye', 'an', 'z', , 'i' ]console.log(name[3]);//undefinedconsole.log(name.length);//5for(var v in name){ console.log(v);//0 1 2 4 }
If you want to change the value of an array element to undefined instead of deleting it, you can use undefined to assign a value instead of using the delete operator.
array element Deletions should use the splice function.
4, Function expression
The function keyword can be used to define an expression in one of the functions. Example of a function expression in a closed place
function expressions are very similar to function declarations (functions statement) and have almost the same syntax. The main difference between a function expression and a function declaration is the function name, which can be ignored in a function expression to create an anonymous function.
anonymous function creation recursion technique
The anonymous function can complete the recursive invocation through the properties of the Arguments.callee. This property usually points to the current (called) function, so it can be used for recursive invocation:
var charsInBody = (function(elm) { if (elm.nodeType == 3) { // TEXT_NODE return elm.nodeValue.length; } var count = 0; for (var i = 0, child; child = elm.childNodes[i]; i++) { count += arguments.callee(child); } return count;})(document.body);
5,get,set operator
The Get,set syntax binds an object property to the function that will be called when the property is looked up.
var log = ['test'];var obj = { get latest () { if (log.length == 0) return undefined; return log[log.length - 1] }, set current (str) { log[log.length] = str; }}obj.current = 'fa';console.log (obj.latest);//输出 "test".
7,in
If the specified property exists in the specified object, the in operator returns TRUE.
// 数组var trees = new Array("ye", "an", "zhi");0 in trees // true6 in trees // false"bay" in trees // false (必须使用索引号,而不是数组元素的值)"length" in trees // true (length是一个数组属性)
Use the delete operator and assign a property to a value of undefined
var name = ["ye","an","z","h","i"];delete name[3];3 in name; // 返回false
8,instanceof
The instanceof operator can be used to determine whether the prototype property of a constructor exists on another prototype chain to detect the object.
This operator will be explained in "Objects and prototypes"
9,let operator
Explained in the previous variable scope
10,new operator
This operator will be explained in "Objects and prototypes"
11,this operator
The This keyword in a JavaScript function has many different behaviors than other languages. It is also slightly different in the strict and non-strict mode of JavaScript. In most cases, the way the function is called determines the value of this. This cannot be assigned during execution, and the value of this may be different at each time the function is invoked. ES5 introduced the Bind method to set the this value of the function, regardless of how the function was called.
11.1 Global Context Context
In the global run context (outside any function body), this refers to the global object, whether in strict mode or not.
this===window //true
11.2 Function Context
Inside the function, the value of this depends on how the function is called.
In non-strict mode, the value of this is an object and is the global object by default
function f1(){ return this;}f1() === window; // global object
Strict mode should return undefined, but this does not have a wide range of support in the browser, typically returns a Window object
11.3As as an object method
Functions are invoked as methods in an object, their this is set by the object that invokes the function.
var o = { prop: 37, f: function() { return this.prop; }};console.log(o.f()); // logs 37
11.4 as a constructor as a constructor
The so-called constructor is to generate a new object by this function (object). At this point, this is the new object.
var x = 2; function test(){ this.x = 1; } var o = new test(); alert(x); //2 alert(o.x); //1
11.5 Apply Call
Apply () is a method of a function object that changes the calling object of a function, and its first parameter represents the changed object that called the function. Therefore, this is the first parameter. In other words, JS inside this can be changed
var val = hi; function Test(hello){ this.val = hello; } Test.prototype.printval = function(){ console.log(this.val); } var o = new Test('hello'); o.printval();//hello o.printval.apply();//0 o.printval.apply(o);//hello
The global object is called by default when the argument to apply () is empty.
The first output Hello proof this is the object o
Then output hi to prove that this is a global variable
The last output hello proves that this is reset to object O's
Other than that
Apply has a twin brother Call,call and apply are meant to change the context in which a function runs, in other words, to change the direction of this within the function body. Because JavaScript functions have a concept of "context at definition" and "runtime context" and "context can be changed."
The two work exactly the same way, except that they accept the parameters differently.
In JavaScript, the number of parameters of a function is not fixed, so to say the applicable conditions, when your parameters are clearly known quantity, with call, but not sure, with apply, and then put the parameter push into the array to pass in. When the number of arguments is indeterminate, the function can also traverse all the arguments by arguments the array.
var x = 0;
function Test () {
alert (this.x);
}
var o={};
o.x = 1;
O.M = test;
O.m.apply (); 0
12,typeof operator
The typeof operator returns a String that represents the type of an operand (unevaluated operand) that is not evaluated.
This is used more in the reflection of JS.
It is worth saying that the value of typeof null is object and the value of typeof undefined is undefined
And you need to be aware of that.
typeof Math.LN2 === 'number';typeof Infinity === 'number';typeof NaN === 'number'; // 尽管NaN是"Not-A-Number"的缩写,意思是"不是一个数字"typeof Number(1) === 'number'; // 不要这样使用!// 下面的容易令人迷惑,尽量不要用typeof new Boolean(true) === 'object';typeof new Number(1) ==== 'object';typeof new String("abc") === 'object';
Attention
1, regular expression literals do not conform to the standard in some browsers
typeof /s/ === 'function'; // Chrome 1-12 ... // 不符合 ECMAScript 5.1typeof /s/ === 'object'; // Firefox 5+ ... // 符合 ECMAScript 5.1
2, any attribute in the prototype chain will produce a value
typeof flight.toString // functiontypeof flight.constructor// function
We have two ways to get rid of these unwanted properties, one is to do the detection in the program, throw away the value of the function of the property, because we usually need data in the project encoding is not a function, the second is to use the hasOwnProperty () method, if the object has a unique property, will return True
13,void operator
The void operator evaluates its operand expression and ignores the result of the evaluation, returning directly to the undefined
Often someone uses void (0) or void to represent the undefined value instead of the undefined variable, because they fear that the value of the undefined variable may not be undefined
Often someone uses void (0) or void to represent the undefined value instead of the undefined variable, because they fear that the value of the undefined variable may not be undefined
void function iife() { var bar = function () {}; var baz = function () {}; var foo = function () { bar(); baz(); }; var biz = function () {}; foo(); biz();}();
When a user clicks on a URI that begins with a javascript: protocol, the browser evaluates the code after the colon and then displays the result of the evaluation on the page, which is basically a large space, which is usually not what we want. The browser does not do this stupid thing only when the evaluation result of this code is undefined, so we often use the void operator to implement this requirement. Like this:
<a href="javascript:void(0);"> 这个链接点击之后不会做任何事情,如果去掉 void(), 点击之后整个页面会被替换成一个字符 0。</a><a href="javascript:void(document.body.style.backgroundColor='green');"> 点击这个链接会让页面背景变成绿色。</a>
Note that while this is possible, it is not recommended to use JavaScript: Pseudo-Protocol to execute JavaScript code, and the recommended practice is to bind the click event to the LINK element.
14,yield operator
Say that yield will have to mention the generator function, the introduction of the generator function in ECMAScript 6, the function is to return an internal state of the Walker, the main feature is the function of the internal use of the yield statement.
When the generator function is called, the function does not execute, but instead returns a walker (which can be interpreted as a paused execution). Later, each time the next method of the Walker is called, it executes from the head of the function body or the last stop (which can be understood as recovery execution) until the next yield statement is encountered and returns the value of the yield statement.
ECMAScript the generator function as defined in draft 6, you need to add an asterisk following the function keyword. The yield statement is then used inside the function to define each member of the walker.
function* helloWorldGenerator() { yield 'hello'; yield 'world';}var hw = helloWorldGenerator();hw.next() // { value: 'hello', done: false }hw.next()// { value: 'world', done: false }hw.next()// { value: undefined, done: true }hw.next()// Error: Generator has already finished
Yield is somewhat similar to the return statement, and can return a value. The difference is that each time yield is encountered, the function returns the value of the expression immediately following yield, pauses execution, resumes execution from that position the next time, and the return statement does not have the function of positional memory.
The above code defines a generator function Helloworldgenerator, whose walker has two members "Hello" and "world". Call this function and you will get the walker.
I will use a space in the late "special features and techniques" to introduce yield, which is an essential tool for the KOA framework to achieve the core concept of "reducing the callback pyramid".
Next, we will go on to the next day to learn the JavaScript function.
First day: JavaScript variables and Expressions (2)