1. 构造函数
1.1 this的指向
- 指向 ```javascript function Car(color){ this.color = color; } //在未实例化构造函数时,this不存在
Car(); //在执行构造函数时,this存在且指向windows
var car = Car(red); //实例化后,this指向实例化对象
2. 原理```javascriptfunction Car(color, brand){this.color = color;this.brand = brand;//return this; -> 隐式返回了一个this}var car1 = new Car('red', 'Benz');//实例化后的过程:/*AO{this: {} //在AO生成一个this对象}function Car(color, brand){this = {color : red,brand : Benz} //此时this指向实例化对象this.color = color;this.brand = brand;}*/console.log(car.color);//因此 在实例化对象中调用color可以取出AO的this中的color/*破坏构造函数*/function Car(color, brand){this.color = color;this.brand = brand;//return this; -> 隐式返回了一个thisreturn {};//如果手动返回了引用值{},[],function(),就会破坏构造函数}var car1 = new Car('red', 'Benz');console.log(car1);//{}
2. 包装类
2.1 原始值的字符串的length方法
var str = 'abc';console.log(str.length); //3/*原理:str.length -> new String(str).length*/
2.2 数组的截断方法
var arr = [1, 2, 3, 4, 5];arr.length = 3;console.log(arr); // [1, 2, 3]arr = [1, 2, 3, 4, 5];arr.length = 6;console.log(arr); // [1, 2, 3, 4, 5, empty]//若是字符串var str = 'abc';str.length = 1;/*原理:str.length = 1 -> new String(str).length = 1 -> delete new String(str).length*/console.log(str); //abc//笔试题//1.var name = 'languiji';name += 10;var type = typeof(name);if(type.length === 6){type.text = 'string';/*new string(type).text = 'string';delete;*/}console.log(type.text);//2.
2.3 笔试题 ❓
//笔试题//1.var name = 'languiji';name += 10;var type = typeof(name);if(type.length === 6){type.text = 'string';/*new string(type).text = 'string';delete;*/}console.log(type.text);//2.function Test(){var d = 1;function f(){d++;console.log(d);}this.g = f;}var test1 = new Test();test1.g();//2test1.g();//3var test2 = new Test();test2.g();//2 ❓实例化后的AO有2个吗?//3.var x = 1,y = z = 0;function add(n){return n = n + 1;}y = add(x);function add(n){return n = n + 3;}z = add(x);console.log(x, y, z);//1 4 4//4.function foo1(x){console.log(arguments);return x;}foo1(1,2,3,4,5); //能打印function foo2(x){console.log(arguments);return x;}(1,2,3,4,5);(function foo3(x){console.log(arguments);return x;})(1,2,3,4,5);//能打印//5function b(x, y, a){a = 10;console.log(arguments[2])}b(1, 2, 3);//10
3.作业
/*写一个函数,接受任意一个字符串,算出这个字符串的总字节数(0-255位位1个字节,其后为2个字节) str.charCodeAt(字符下标)*/function test(str) {var sum = 0;for (var i = 0; i < str.length; i++) {var item = str.charCodeAt(i);if (item <= 255) {sum += 1;} else {sum += 2;}}return sum;}console.log(test("abc"));//第二种办法function test(str){var sum = str.length;for(var i = 0;i < str.length; i++){var item = str.charCodeAt(i);if(item > 255){sum++;}}return sum;}console.log(test("abc你好"));
