常用
严格模式 use strict
- 必须使用var声明变量
- 禁止自定义函数this指向window
'use strict'
funcion Person(name){
this.name = name;
}
Person("Tom"); //error
new Person("Tom"); //right
JSON对象
JSON.stringify(obj/arr)
js对象(数组)转json对象(数组)
JSON.parse(json)
json对象转(数组)js对象(数组)
Object扩展
Object.create(prototype, [descriptors])
以指定对象为原型创建新的对象
var man = {sex:'mail'};
var person = Object.create(man, {
name: {
value: '',
writable: true, //可写
configurable: true, //可配置(可删除)
enumerable: true //可枚举
}
})
person.name = 'Tom';
for (let value in person) {
console.log(value); //name sex
}
Object.defineProperties(object, descriptors)
为指定对象定义扩展多个属性
var obj1 = {
firstName: 'Kevin',
lastName: 'Tseng'
};
Object.defineProperties(obj1, {
fullName: {
//获取
get: function(){
return this.firstName + '-' + this.lastName;
},
//监听
set: function(data){
var nameArr = data.split("-");
this.firstName = nameArr[0];
this.lastName = nameArr[1];
}
}
})
console.log(obj1.fullName); //Kevin-Tseng
obj1.fullName = "Tom-Smith";
console.log(obj1.fullName, obj1.firstName); //Tom-Smith Tom
Array扩展
- indexOf()
- lastIndexOf()
- forEach(function(item, index){})
- map(function(item, index){})
- filter(function(item, index){})
Function扩展
- call()
Function.call(obj, arguments) 将函数送给某对象,立即执行
- apply()
Function.apply(obj, [arguments]) 将函数送给某对象,立即执行
- bind()
Function.call(obj, arguments) 将函数送给某对象,调用执行
var obj = {name: 'Kevin'};
function foo(data){
console.log(this, data);
}
foo.call(obj, 33);//{name: "Kevin"} 33
foo.apply(obj, [28]);//{name: "Kevin"} 28
foo.bind(obj)(22); //{name: "Kevin"} 22
setTimeout(function(data){
console.log(this, data); //{name: "Kevin"} 18
}.bind(obj, 18),1000);