@EncyKe
2016-05-09T10:01:06.000000Z
字数 8953
阅读 4203
前端
JavaScript
JS属于弱类型语言,命名时无需指定数据类型。含六种数据类型:五种原始类型以及object:
+
/-
可以隐式转换数据类型(number <-> string)
// string → number
str - '';
// number → string
num + '';
// 可实现a、b赋值为1,但b赋值后为全局变量;不推荐;
var a = b = 1;
// 推荐写法;
var a = 1,
b = 1;
// 或者:
var a = 1;
var b = 1;
严格等于:===
,必须在数据类型全等的情况下才返回true。
注意:NaN ≠ NaN、[] ≠ []、{} ≠ {},即NaN === NaN
、[] === []
、{} === {}
均将返回false。
用法:typeof obj
,返回obj的类型字符串。
注意:typeof null; typeof Array;
均将返回object。
用法:obj instanceof Object
,返回obj是否为Object的布尔值。
用法:Object.prototype.toString.apply(obj)
,返回obj的类型字符串。
或者(进阶用法):
用法:getType(obj)
function getType(obj){
return Object.prototype.toString.call(obj).slice(8,-1)
}
[1,2]
、[1,,2]
)、对象(如:{x=1,y=2}
)的初始化表达式;var fn = function() {};
或者(function() {})();
;obj.prop;
或者obj['prop'];
;fn();
;new Object;
;? :
;,
;delete
删除对象属性,使之为undefined;
try{
// 执行;
}catch{
// 异常处理;
}finally{
// 不管异常与否均要执行;
}
注意:catch和finally必有其一。
use strict;
with(){}
不利于引擎调用、可读性差);
var obj = {
x:1,
y:2
};
function fn(){}
var obj = new fn();
有限原型链继承:obj → fn.prototype → Object.prototype → null
fn.prototype.z = 1;
obj.z = 1;
'z' in obj;
为真, obj.hasOwnProperty('z');
为假;
var obj = Object.create({x:1});
Object.defineProperty(obj,'prop',{
writable: true,
enumerable: true,
configurable: true,
value: ''
});
// 三个标签默认为false;
Object.defineProperties(obj,{
prop1: {
writable: true,
enumerable: true,
configurable: true,
value: ''
},
prop2: {
writable: true,
value: ''
}
});
// 用于判断,表obj.prop !== undefined || obj.prop !== null
obj.prop != undefined;
// 用于判断,仅表obj.prop !== undefined
obj.prop !== undefined;
Object.getOwnPropertyDescriptor(obj,'prop');
get prop(){
}
set prop(val){
}
function getType(obj){
return Object.prototype.toString.call(obj).slice(8,-1)
}
Object.preventExtensions(obj)
:使对象不可添加新属性;Object.isExtensions(obj)
:对象是否可添加新的属性;Object.seal(obj)
:对象的所有属性configurable为false;Object.frozen(obj)
:对象的所有属性writable、configurable为false;
// obj → JSON;
JSON.stringify({x:1});
// JSON → obj;
JSON.parse('{"x":1}');
var arr = [];
// 按数组长度创建(长度范畴:0 ~ 2^23-1);
var arr = new Array(1024);
// 按添加内容创建;
var arr = new Array(1,2,3,4,5);
arr.push(val);
或者:
arr[arr.length] = val;
arr.unshift(val);
delete arr[index];
index in arr; // => false
或者:
arr[index] = undefined;
index in arr; // => true;
arr.length -= 1;
或者:
arr.pop();
arr.shift();
join()
reverse()
sort()
arr.sort(function(a,b){return a- b;})
concat()
slice()
splice()
forEach()
map()
filter()
every()
some()
reduce()
reduceRight()
indexOf()
lastIndexOf()
Array.isArray(arr);
fnOne(); // 下面为函数声明语句,函数可在它之前被调用;
funcion fnOne(){};
fnTwo(); // 下面为函数表达式,函数不可在它之前被调用;
var fnTwo = funcion(){}
function fn() {}
var fnAlias = function(){}
(function(){})()
或者:
!function(){}()
或者:
+function(){}()
return function() {}
var fnAlias = function fn(){}
应用:递归调用
var fnAlias = function fn(){ fn(); }
注意: NFE的兼容性及报错
var fnAlias = function nfe() {};
alert(fnAlias === nfe);
// IE 6-8: false;
// IE 9+, Ch, FF: error.
var fn = new Function();
或者:
var fn = Function();
或者:
Function();
亦支持立即执行:
Funtion()();
this
关键字与指向上下文this
通常指向当前函数的拥有者,即总是指向调用该方法的对象;this
取决于函数调用的方式;this
指向全局对象 (JS中是window
,node.js中是global
)
function fn() {
console(this);
// this指代全局对象window或global;
}
注意:严格模式下的函数内调用指向undefined。
this
指向对象
var obj = {
prop: '',
fn: function () {
console.log(this.prop);
// this指向对象obj;
}
}
或者:
var obj = { prop: '' };
function f() {
console.log(this.prop);
}
obj.fn = f;
console.log(obj.fn());
this
指向调用的对象
var obj = {
fn: function() {
return this.prop;
}
}
var p = Object.create(obj);
p.prop = 31;
console.log(p.fn()); // => 31;
this
指向对象实例
function Obj() {
this.prop = '';
this.fn = function () {
console.log(this.prop);
}
// this指代对象示例Obj;
}
var obj = new Obj();
call()
或者apply()
方法改变上下文实现继承
var obj = {
prop: '',
fn: function() {
console.log(this.prop);
}
}
obj.fn();
var o= {
prop: '',
}
obj.fn.call(o,prop);
// call方法改变上下文,把fn方法中this指向的obj改为指向o;
或者(上述这一调用方法不太友好,亦可用构造函数):
function Obj() {
this.prop = '';
this.fn = function() {
console.log(this.prop);
}
}
function OofObj() {
Obj.call(this.prop);
}
var o = new OofObj();
o.prop();
用法:
function fn(c, d) {
return this.a + this.b + c + d;
}
var obj = {
a: 1,
b: 2
}
fn.call(obj, 3, 4); // => 1 + 2 + 3 + 4
fn.apply(obj, [3,4]); // => 1 + 2 + 3 + 4
bind()
方法进行绑定
function fn() {
return this.prop;
}
var g = fn.bind({prop:'test'});
console.log(g()); // =>test;
var o = {prop: 31, fn: fn, g: g};
console.log(o.fn(),o.g()); // =>31, 'test'
用法(currying):
function fn(a, b, c) {
return a + b + c;
}
var func1 = fn.bind(undefined, 100);
func1(1,2); // => 100 + 1 + 2;
var func2 = func1.bind(undefined, 200);
func1(10); // => 100 + 200 + 10;
bind()是ES 5新特性,兼容性模拟如下:
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('What is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP? this : oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
function fn(x,y,z) {
arguments.length; // 取得实参个数;
}
fn(1,2);
fn.length; // 取得形参个数;
优点:灵活、方便、可封装;
缺点:空间浪费、内存泄露、性能消耗;
避免提升:
for (var i = 1; i < 4; i++) {
!function(i) {
console.log(i); // 1, 2, 3
}(i);
}
封装变量:
(function() {
var _userId = 31;
var _typeId = 'item';
var export = {};
function converter(userId) {
return +userId;
}
export.getUserId = function() {
return converter(_userId);
}
export.getTypeId = function() {
return _typeId;
}
window.export = export;
}());
export.getUserId(); // 31
export.getTypeId(); // item
export._userId; // undefined
export._typeId; // undefined
export.converter; // undefined
作用域链:
function outer2() {
var local2 = 1;
function outer1() {
var local1 = 1;
// visit local1, local2 or global3
}
outer1();
}
var global3 = 1;
outer2();
注意:
function outer() {
var i = 1;
var func = new Function("console.log(typeof i);");
func(); // =>undefined
}
outer();
Student.prototype = Person.prototype; // 不推荐使用,同步机制;
或者:
Student.prototype = new Person(); // 不推荐使用,传参不明;
或者:
Student.prototype = Object.create(Person.prototype);
Person.prototype.constructor = Person;
if (!Object.create) {
Object.create = function(proto){
function F(){};
F.prototype = proto;
return new F
};
}
/abc/gim.test('abc');
或者:
RegExp('abc','gim').test('abc');
符号 | 匹配字符串 |
---|---|
. |
任意字符 |
\d |
数字0~9 |
\D |
非\d ,除数字0~9的其它字符 |
\w |
数字0~9、字母a~z/A~Z、_ |
\W |
非\w |
\s |
Space、Tab、换页、换行 |
\S |
非\s |
\t |
Tab |
\r |
Enter |
\n |
换行符 |
\f |
换页符 |
\v |
垂直制表符 |
[] |
字符范围 |
[^] |
字符范围以外 |
^ |
行首 |
$ |
行尾 |
\b |
零宽单词边界 |
\B |
非\b |
(x) |
分组 |
\数字 |
表用分组匹配到的字符串 |
(?:x) |
仅分组不引用 |
* |
贪婪算法,任意匹配,次数>=0 |
+ |
贪婪算法,任意匹配,次数>0 |
x*? |
非贪婪算法,同* |
x+? |
非贪婪算法,同+ |
x? |
出现0或1次 |
`x | y` |
x{数字n} |
x重复次数为n |
x{数字n,} |
x重复次数大于等于n |
x{数字n,数字m} |
x重复次数满足:n <= x <= m |
g
:global,全局匹配;
i
:ignoreCase,不区分大小写;
m
:multiline,跨行匹配;