1. 对象的构成
属性 + 方法
var teacher = {
name: "Tom",
age: 32,
sex: "male",
weight: 130,
teach: function() {
console.log("I am teaching JavaScript")
}
}
2. 对象的操作
查
- 增
- 改
- 删
delete teacher.sex; delete teacher.teach;
3. this
例1:
例2:课堂考勤管理var teacher = {
name: "Tom",
age: 32,
sex: "male",
weight: 130,
teach: function() {
console.log("I am teaching JavaScript")
},
smoke: function() {
// teacher.weight --
this.weight --;
// console.log(teacher.weight);
console.log(this.weight);
},
eat: function() {
// teacher.weight ++
this.weight ++;
// console.log(teacher.weight);
console.log(this.weight);
}
}
var attendance = {
students: [],
total: 6,
join: function(name) {
this.students.push(name);
if (this.students.length === this.total) {
console.log(name + "到课,学生已到齐");
} else{
console.log(name + "到课,学生未到齐");
}
},
leave: function(name) {
var idx = this.students.indexOf(name)
if( idx !== -1) {
this.students.splice(idx, 1)
}
console.log(name + "早退")
console.log(this.students);
},
classOver: function () {
this.students = [];
console.log("已下课")
}
}
4. 构造函数创建对象
4.1 系统自带的构造函数
与对象字面量没有区别 ```javascript // 对象字面量 var teacher = { name: “Tom”, age: 32, } obj.age = 28;
// 自带的Object构造函数 var obj = new Object(); obj.name = “Tom”; obj.age = 23;
<a name="x5vBc"></a>
#### 4.2 自定义构造函数
- 大驼峰
```javascript
function Teacher() {
this.name = "Tom";
this.sex = "male";
this.weight = 100;
this.eat = function () {
this.weight += 2;
console.log(this.weight)
}
}
var teacher = new Teacher();
// 构造函数传参
function Teacher(opt) {
this.name = opt.name;
this.sex = opt.sex;
this.weight = opt.weight;
this.eat = function () {
this.weight += 2;
console.log(this.weight)
}
}
var teacher = new Teacher({name: "张三", sex: "male", weight: 112})
- 构造函数生成的对象是独立的,对象A属性的改变不会影响对象B
- 正式开发时构造函数需使用opt对象来传参
5. 构造函数与实例化原理
```javascript function Car(color, brand) { // this = {}; this.color = color; this.brand = brand; // return this; }
var car1 = new Car(‘red’, ‘Benz’);
GO = { Car: (function), car1: Car{color: ‘red’, brand: ‘Benz’} }
AO = { this: {}, // 当使用new关键字执行时,自动在AO中创建一个this对象 }
**this指向问题**
- 未执行时, this无意义
- 作为普通函数执行时`Car()`,this为window
- 作为构造函数执行时`new Car()`,会在AO中创建一个新的对象,并将this指向这个对象,函数执行结束后返回这个对象,即**改变this指向**
**构造函数返回值**
- 未指定返回值时,自动返回实例化对象
- 指定返回值时
- 当返回原始值,无效,还是返回实例化对象
- 当返回引用值时(对象,数组,函数),返回该引用值
<a name="hQC2z"></a>
### 6 包装类
```javascript
// 原始值没有自己的属性和方法
var a = 1; // a 是原始值
a.len = 3; // new Number(a).len = 3; delete
a.len // undefined
// 数字不一定都是原始值
var b = new Number(a); // b 是对象,可以设置 属性和方法
b.len = 3;
b // Number(1, len: 3)
// Number 对象可以参与运算,返回原始值
var c = b + 1;
c // 2
// String
var str = 'abc';
console.log(str.length) // console.log(new String(str).length) -> 3
str.length = 1; // new String(str).length = 1; delete;
console.log(str.length) // console.log(new String(str).length) -> 3
系统内置的三个包装类
Number(), String(), Boolean()
7. 练习
写一个构造函数,接收数字类型的参数,参数数量不定,完成参数相加和相乘的功能。 ```javascript // 方法1 function Compute() { var args = arguments, res; this.getSum = function() { res = 0; for(var i = 0; i < args.length; i++) { res += args[i] } console.log(res) };
this.getProduct = function() { res = 1; for(var i = 0; i < args.length; i++) { res *= args[i] } console.log(res) } }
// 方法2 function Compute() { var args = arguments;
function loop(method, res) { for(var i = 0; i < args.length; i++) { var item = args[i]; if(method === ‘add’) { res += item } else if (method === “mul”) {res *= item} } console.log(res) }
this.getSum = function() { loop(“add”, 0); };
this.getProduct = function() { loop(“mul”, 1); } }
var compute = new Compute(1, 2, 3, 4, 5); compute.getSum(); compute.getProduct();
// 方法3
function Compute() {
function loop(args, method, res) {
for(var i = 0; i < args.length; i++) {
var item = args[i];
if(method === ‘add’) { res += item }
else if (method === “mul”) {res *= item}
}
console.log(res)
}
this.getSum = function() { loop(arguments, “add”, 0); };
this.getProduct = function() { loop(arguments, “mul”, 1); } } var compute = new Compute(); compute.getSum(2, 4, 6); compute.getProduct(3, 5, 7);
2. 消费者与车
写一个构造车的函数,可设置车的品牌,颜色,排量;再写一个构造消费者的函数,设置用户的名字,年龄,收入,通过选择的方法实例化该用户喜欢的车,再设置车的属性。
```javascript
function Car(opt) {
this.brand = opt.brand;
this.color = opt.color;
this.capacity = opt.capacity;
}
function Consumer(opt) {
this.name = opt.name;
this.age = opt.age;
this.income = opt.income;
this.selectCar = function() {
this.favorCar = new Car(opt.carOpt);
console.log(this.favorCar)
}
}
var consumer = new Consumer({
name: "Alex",
age: 32,
income: 100000,
carOpt: {
brand: 'Tesla',
color: "silver",
capacity: 20
}
});
consumer.selectCar()
构造函数与闭包 ```javascript function Test(a, b) { var c = 1; this.a = a; this.b = b;
function f() { c++; console.log(c); }
this.g = f; }
var test1 = new Test(); test1.g(); // 2 test1.g(); // 3 var test2 = new Test(); test2.g(); // 2
4. 预编译
```javascript
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
- 立即执行函数 ```javascript function foo1(x) { console.log(arguments); return x; }
foo(1, 2, 3, 4, 5); // [1,2,3,4,5]
function foo2(x){ console.log(arguments); return x; }(1,2,3,4,5); // 5
(function foo3(x){ console.log(arguments); return x; })(1,2,3,4,5); // [1,2,3,4,5]
6. 形参实参映射
```javascript
function b(x, y, a) {
a = 10;
console.log(arguments[2]); // 10
arguments[2] = 10;
console.log(a); // 10
}
b(1, 2, 3)
ASCII码:表1: 0-127, 表2: 128-255 一个字节 byte
UNICODE码,涵盖ASCII码, 2个字节
var str = 'a';
// string.charCodeAt() -> 返回字符串某位置上字符的unicode码
var pos = str.charCodeAt(0);
pos // 97
写一个函数,接收任意一个字符串,算出这个字符串的总字节数
function getBytes(str) {
var bytes = 0;
for(var i = 0; i < str.length; i++) {
var charCode = str.charCodeAt(i);
if (charCode <= 255) {
bytes += 1;
} else {
bytes += 2;
}
}
return bytes;
}
getBytes("Tom, 你好,我是Alex"); // 19
8. 其他
- 数组的截断方法
var arr = [1, 2, 3, 4, 5]
arr.length = 3;
console.log(arr) // [1, 2, 3]