#目錄
bind / call / apply (點撥)
bind()方法創建一個新的函數, 當被調用時,將其this關鍵字設置爲提供的值,在調用新函數時,在任何提供之前提供一個給定的參數序列。
我的理解: 允許你改變當前function 的相應this的作用
"use strict";
//this的值被bind改變了
function locate() {
console.log(this.location)
}
function Marn(location) {
this.location=location;
}
var kitty = new Marn('my bind');
//這裏的kitty就是this 的改變者
var locateBind=locate.bind(kitty); //強度理解.換成了kitty:this.prototype
locateBind();
//還有這裏我們換成call
var kittyCall = new Marn("my call");
locate.call(kittyCall);
//還有這裏我們換成apply
var kittyApple = new Marn("my apply");
locate.apply(kittyCall);
object (ES5+)
Object.getPrototypeOf
Object.getOwnPropertyDescriptor
Object.getOwnPropertyNames
Object.create
方法創建一個擁有指定原型和諾幹屬性的對象
Object.defineProperty
//**控制對象屬性**
var cat = {};
Object.defineProperty(cat, "name", {
value: "Maru",
writable: false, //寫
enumerable: true, //枚舉
configurable: false //可否配置
});
Object.defineProperty(cat, "skill", {
value: "exploring boxes",
writable: true,
enumerable: true,
configurable: true
});
Object.defineProperties
Object.seal
Object.freeze
Object.preventExtensions
Object.isSealed
Object.isFrozen
Object.keys
//這個很常用,操作對象等
var nums={
"first":7,
"second":14,
"third":13
};
//這樣就很容易的拿到值了
var test = Object.keys(nums);
for (var i=0;i<test.length;i++){
console.log(nums[test[i]])
}
this (面試全解)
//example 01
function test() {
console.log(this.m)
}
this.m=100
window.test(); //這裏的this是window
//example 02
this.m=1000;
var obj={
m:100,
test:function(){
console.log(this.m)
}
}
obj.test();>>100
//example 03 閉包裏面的this
this.m = 1000;
var obj = {
m: 100,
test: function () {
// console.log(this.m);//100
return function () {
console.log(this.m)
//這裏被返回到外層函數,在window全局下. 此時的this 是1000;
}
}
}
obj.test()();>>1000
//example 04在DOM事件上的this指向
<!DOCTYPE html>
<html lang="en">
<body>
<input type="button" value="test" id="test" style="color: red">
</body>
<script>
var style={
color:"green"
};
function test() {
console.log(this.style.color)
}
document.getElementById("test").οnclick=test;
</script>
</html>
//example 05 面向對象的this
this.a = 1000;
function test() {
this.a = 1;
}
test.prototype.getA = function () {
return this.a;
};
var p = new test;
console.log(p.getA())
// p調用了getA ;
// p new test構造函數, 所以最後掛載帶test()函數裏面的a了
JSON (高階)
JSON.parse(text,[,reviver])
//
var result = JSON.parse('{"a": 1, "b": "2"}', function(key, value){
if (typeof value == 'string'){
return parseInt(value);
} else {
return value;
}
//result.b 2
確保解析的時候是們需要的數據
JSON.stringify(value [, replacer [, space]])
JSON.stringify允許作者接受一個ECMAScript值然後轉換成JSON格式的字符串。 在其最簡單的形式中,JSON.stringify接受一個值返回一個字符串,
var mike = JSON.stringify({mike: "taylor"})
mike>>'{"mike": "taylor"}'
typeof mike >>"string"
如果replacer方法返回undefined, 則鍵值對就不會包含在最終的JSON中。
var nums = {
"first": 7,
"second": 14,
"third": 13
}
var luckyNums = JSON.stringify(nums, function(key, value){
if (value == 13) {
return undefined;
} else {
return value;
}
},2);//這裏的2 是打印出來的縮進2個字符,在開發node 比較實用
console.log(luckyNums)>>'
{
"first":7,
"second":14
}'