Javascript
介绍
概要
- js 使动态内容更新成为可能
- web page js分: browser api, third api
- js 存在执行顺序
- js 属于解释性语言,逐句解释逐句执行,得到返回结果,返回结果可能参与下句执行。
- js 字符串文本执行,采用just-in-time 编译改进运行时性能,依然是解释性语言。
async | defer
- js 相关的dom操作,需要dom存在;或者为了提升性能,我们添加async and defer。
相同点: 不阻塞dom解释,渲染
不同点: async: js彼此不能有依赖;defer,彼此之间按顺序加载,于依赖。
使用注意事项
定义事项
- 尽可能使用let,避免var,减少重复变量定义,引起的逻辑错误
- 类定义了属性和方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15function Person(first, last, age, gender, interests) {
this.name = {
first : first,
last : last
};
this.age = age;
this.gender = gender;
this.interests = interests;
this.bio = function() {
alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
};
this.greeting = function() {
alert('Hi! I\'m ' + this.name.first + '.');
};
}
对象创建方法
字面量 var obj = {a:2,age:28}
function new 创建
new Object()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15let person1 = new Object();
person1.name = 'Chris';
person1['age'] = 38;
person1.greeting = function() {
alert('Hi! I\'m ' + this.name + '.');
};
//or
let person1 = new Object({
name: 'Chris',
age: 38,
greeting: function() {
alert('Hi! I\'m ' + this.name + '.');
}
});Object.create(),但是ie8不支持
1
2#从已存在的对象中copy
let person2 = Object.create(person1);原型
对象的原型
Since ECMAScript 2015, you can access an object’s prototype object indirectly via Object.getPrototypeOf(obj).
1
2# __proto__ 已废弃
Object.getPrototypeOf(p1)构造函数的原型
也是对象,也存在属性和方法
1
Person.prototype;
两者关系
1
Object.getPrototypeOf(p1) === Person.prototype;
构造函数
构造
原型对象都有构造函数属性constructor,指向最开始的构造函数
也就是任何对象,都有构造函数属性1
2Object.getPrototypeOf(p1) == Person.prototype
p1.constructor() → Person.prototype.contructor()call,修改函数指向为当前上下文
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16function Teacher(first, last, age, gender, interests, subject) {
Person.call(this, first, last, age, gender, interests);
this.subject = subject;
}
等效于
function Teacher(first, last, age, gender, interests, subject) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
this.subject = subject;
}原型继承需要修改construcotr
Person.prototype.constructor指向Person,那么原型链上的Teacher.prototype与其实例constructor都会指向Person
1
Teacher.prototype = Object.create(Person.prototype);
修改Tearch.prototype,
1
2
3
4Object.defineProperty(Teacher.prototype, 'constructor', {
value: Teacher,
enumerable: false, // so that it does not appear in 'for in' loop
writable: true });Class | extends
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26class Person {
constructor(first, last, age, gender, interests) {
this.name = {
first,
last
};
this._age = age;
this.gender = gender;
this.interests = interests;
}
greeting() {
console.log(`Hi! I'm ${this.name.first}`);
};
farewell() {
console.log(`${this.name.first} has left the building. Bye for now!`);
};
get age(){
return this._age;
}
set age(value){
this._age = value;
}
}
参考
JavaScript
Objects
赏
使用支付宝打赏
使用微信打赏
若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏