自 ES2015 起,JS 引入let 和 const 关键词定义变量的块作用域(Block Scope)。
var 仅支持全局作用域(Global Scope)和函数作用域(Function Scope);
let 支持块作用域,即严格定义作用域在花括号{}里面;
counst 不仅支持块作用域,且定义的变量无法再修改。
var i = 5;
for (var i = 0; i < 10; i++) {
// some statements
}
// Here i is 10
let i = 5;
for (let i = 0; i < 10; i++) {
// some statements
}
// Here i is 5
for 循环for (let i = 0; i < arr.length; i++) {
// do iteration
}
for (let val of arr) {
// loop over values of array
}
for (let key in obj) {
// loop over keys of object
}
let brother = {
name: ‘Alex‘,
age: 25,
sayHello: function () {
return ‘Hello!‘ + ‘my name is‘ + this.name;
}
}
function Person (name, age, gender) {
this.name = name;
this.gender = gender;
this.age = age;
sayHello: function () {
return ‘Hello!‘ + ‘my name is‘ + this.name;
}
}
let brother = new Person(‘Alex‘, 25, ‘male‘);
let brother = new Object({
name: ‘Alex‘,
gender: ‘male‘
age: 25,
sayHello: function () {
return ‘Hello!‘ + ‘my name is‘ + this.name;
}
})
Object.create() methodlet brother = {
name: ‘Alex‘,
gender: ‘male‘
age: 25,
sayHello: function () {
return ‘Hello!‘ + ‘my name is‘ + this.name;
}
}
let sister = Object.create(brother);
sister.name = ‘Alice‘;
sister.gender = ‘female‘
补充:
sister = Object.create(brother) 在这里实际上是以 brother 作为原型构建的,亦即:
sister.__proto__ === brother
将返回 true。
我们刚刚创建的brother 对象的 constructor 是 Person(),而 Person() 的原型是 Object()。如果我们运行:
brother.valueOf();
将列出 brother 中所有的属性和方法。但是,Person() 中并没有 valueOf() 方法,因此可以看出实际上 Person() 实际上继承了 Object() 中的方法 valueOf()。
目前主流浏览器都支持:
brother.__proto__;
自 ECMAScript 2015 开始,也可以:
Object.getPrototypeOf(brother);
每个对象都有个属性 prototype, 例如 Object.prototype,Person.prototype。
Object.prototype 本身是一个对象,里面是 Object 的所有可继承成员。换句话说,prototype 里面不包含的成员是无法继承的。
我们可以直接给对象 bother 添加属性
brother.education = ‘Bachelor of Computer Science‘;
也可以给对象原型 Person 添加属性
Person.prototype.nationality = ‘Chinese‘
我们可以直接给对象 bother 添加方法
brother.coding = function(){
return ‘0 warning(s), 0 error(s)‘;
};
也可以给对象原型 Person 添加属性
Person.prototype.play = function(){
return ‘Happy‘;
};
现在,假设我们想从 Person 构建一个 Student 子类。
首先需要构造函数(constructor function):
function Student(name, age, gender, degree) {
Person.call(this, name, age, gender);
this.degree = ‘Undergraduate‘;
}
此时,构造函数 Student() 的原型属性(prototype property)Student.prototype 并不具有 Person 里带有的方法, 因此还需要继承 Person 的方法。
例如, sayHello() 是Person 的方法,却不在 Student.prototype 中。
Student.prototype = Object.create(Person.prototype)
以 Person.prototype 为原型构建对象并赋给 Student.prototype 就可以继承到 Person 的方法了。
但仅仅这样会造成另一个问题。由于 Student.prototype === Person.prototype,造成了 Student.prototype.constructor === Person.prototype.constructor。因此需要将 Student 的构造函数恢复成 Student 而不是 Person。
Student.prototype.constructor = Student
这样,继承就完成了。
Written with StackEdit.
原文:https://www.cnblogs.com/LexLuc/p/9759697.html