面接前の基礎が必要です.
1186 ワード
jsの中のthis call apply bind
var a = {
a: 'haha',
getA: function () {
console.log(this.a);
}
};
var b = {
a: 'hello'
};
var getA = a.getA;
var getA2 = getA.bind(a);
function run (fn) {
fn();
}
//
a.getA();//haha
//this a
getA();//a
// this this, ,fn()=this.fn(), this
run(a.getA);//a
// fn = a.getA = a getA ,fn()this 。 a
getA2.call(b);// 'haha'
//call(b) 。getA.bind(a) 'haha'
原型function clone(obj) {
//
}
var a = {name:'a'};
var b = clone(a);
// ,
console.log(b.name)//'a'
a.name = 'a1';
console.log(b.name)//'a1'
b.name = 'b';
console.log(b.name)//'b'
console.log(a.name)//'a1'
a.name = 'a2';
console.log(b.name)//'b'
// b ,b a , b ,ab
function clone(obj){
return Object.create(obj);
}
function clone(obj){
function fn(){};
fn.prototype = obj
return new fn();
}
function clone(obj) {
var ret = {};
ret.__proto__ = obj;//__proto__
return ret;
}