使用TypeScript开发已经一段时间了,也把JavaScript遗忘在一边了。今天回过头来学习学习基础,才发现自己是多么的辣鸡。
好高骛远,总是看而少动手敲和记录下来。如此的学习方式,难以深入发展。以后要多码字才行,记录在自己的有道云笔记里,亦或发表在这个平台上。
构造函数
我们可以使用构造函数可以创建我们需要的对象,下面记录几种方式,最主要的区别就在于方法的定义方式。
方式一:
function Person1() {
this.name = `阿布`;
this.age = 11;
this.printInfo = function () {
console.log(`this.name: ${this.name}, this.age: ${this.age}`);
}
}
var per1 = new Person1();
var per2 = new Person1();
console.log(per1.printInfo === per2.printInfo); // false
方法直接定义到构造函数里,这样每声明一个新对象,方法都是同样的,但其地址确实不一样的,浪费空间地址。
方式二
function Person2() {
this.name = `阿紫`;
this.age = 18;
this.printInfo = printInfo;
}
function printInfo () {
console.log(`this.name: ${this.name}, this.age: ${this.age}`);
}
定义了全局函数,污染了全局的命名空间。
方式三
function Person3() {
this.name = `hello pretty`;
this.age = 18;
}
Person3.prototype.printInfo = function (){
console.log(`this.name: ${this.name}, this.age: ${this.age}`);
}
这种方式是比较好的。把方法定义到原型链上,每一个新建的对象都能共用此方法。一般情况下,我们会把共享的方法或属性定义到原型链上。