var a = { user:"Ice", fn:function(e,ee){ console.log(this.user); //Ice console.log(e+ee); } } var b = a.fn; // 申明变量b继承变量a的一个方法 b(1, 2); // underfined NaN b继承了a的方法但是它的this指向的是全局变量 b.call(a,1,2); // call使b的this指向了a b.apply(a,[1,2]); // 同上,区别在于传参不同 b.bind(a); // 这里 bind返回了一个新的函数,这里并不会立即执行
for…in和for…of
for循环相比于用api循环的优点在于可以主动用break结束循环,用return结束函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// for in遍历对象 var obj = {a:1, b:2, c:3}; for (var prop in obj) { console.log(prop); // a b c } // for in遍历数组 var obj = ['a', 'b', 'c']; for (var prop in obj) { console.log(prop); // ‘0’ ‘1’ ‘2’ 由此可见for in会自动添加下标 } //for of遍历数组、字符串、Set、Map等 var a = [{a:1}, {b:2}, {c:3}]; for(let val of a) { console.log(val); // {a:1} {b:2} {c:3} 遍历出值 }
var person = function(name){ this.name = name }; person.prototype.getName = function(){ console.log('名字是:'+this.name); } var aa = new person('cat'); var bb = new person('dog') aa.getName(); //名字是:cat bb.getName(); //名字是:dog console.log(aa.__proto__ === person.prototype); //true console.log(person.prototype.constructor === person); //true
Class
用class改造上面的构造函数。实例化一个对象的时候constructor里面的内容会执行一遍。
1 2 3 4 5 6 7 8 9 10 11 12 13
classperson{ constructor(name) { console.log('constructor执行了'); this.name = name; } getName() { console.log('名字是:'+this.name); } } var a = new person('cat'); var b = new person('dog'); a.getName(); //名字是:cat b.getName(); //名字是:dog