温习日志
——2023年2月12日下午
学习内容
- 构造函数
- 构造函数的名字用大写,如:
const Person = function(name, age) {}
- 构造函数会隐式地创造
this = {}然后将该对象链接到Person.prototype,最终自动返回该对象
- 所有所有的赋值只需要
this.name = name,this.calcAge = function() {}
- 函数不推荐写入构造函数中,因为如果你创造了一千个对象,也会有一千个相同的函数
- 对于构造函数需要
new关键字,如: const su = new Person('su', 22)
- 还有
instanceof运算符,可以查询是否为该原型链上的,如: su instanceof Person
- Prototypes
- 通过
Person.prototype会返回{constructor: Person, 添加的方法}
- 可以在
Person.prototype.calcAge = function() {}这样是在Person.prototype中添加函数,创建的对象通过su.__proto__原型链访问Person.prototype中的函数
- 但是并不推荐这么做,因为这样做有可能会覆盖掉原有的相同名称函数
- 可以通过
Person.prototype.isPrototypeOf(su)查询s的原型链是否为Person.prototype
- 查询是否为自己的属性可以使用
su.hasOwnProperty(要查的属性)
- 原型继承
- 可以通过
Person.prototype.constructor访问Person.prototype原型链的构造函数,也是Person构造函数本身
arr.__proto__ === Array.prototype,他们最终的原型链都是Object.prototype,再赋值__proto__上面便是null
- 练习1,详见于代码
- ES6_Classes
- 类也有类表达式
const PersonCl = class {}
- 也可以直接
class PersonCl {}
- 类中可以包含构造函数,也可以添加私有字段
private只能通过内部访问
- 通过
const su = new PersonCl('su', 2002)创建
su.__proto__ === PersonCl.prototype
- 类没有和函数一样存在提升,也就是不能在声明前使用
- 类内部执行严格模式,即使外部没有开启,内部也会按严格模式执行
posted @
2023-02-12 19:57
这样那样如此如此
阅读(
18)
评论()
收藏
举报