什么是静态属性。
function Web(url) {
this.url = url;
}
let hd = new Web("newJoker");
console.log(hd);
Web.url = "Joker";
console.dir(Web)
第一种打印的url是为我们每一个构造函数实例化出来的对象创建的属性,因此我们把它称为对象属性。
第二种直接使用Web.url的方式是为我们构造函数添加的属性,我们把这种属性称为静态属性。
当我们明白了函数的静态属性之后,再来看看class(类)的静态属性的定义方式。
class User {
title = "Joker";
static title="User的Joker" //静态属性
}
let obj = new User();
console.log(obj);
console.dir(User)
如果我们想给class添加静态属性,只需要在class中定义个属性,并在前面加上static,那这个属性就是为这个class创建的属性。
tips:当我们的属性是提供给所有的实例化对象使用的,我们就可以把这个属性设置为静态属性,能节省内存占用。
什么是静态方法。
function User() {}
User.prototype.show = function () {
console.log('show')
};
User.show = function () {
console.log("static.show");
};
let obj = new User();
console.log(obj);
console.dir(User)
首先大家应该都知道,函数扮演着多个角色,如果函数扮演者构造函数创建出实例化对象的时候,那他调用的就是prototype上的方法。如果函数作为对象被使用的时候,那么它用的就是__proto__上的方法。因此,上述代码中为函数的实例化对象添加的show方法就称为普通方法,而为User本身添加的方法,就称为静态方法。
当我们明白了函数中的静态方法之后,再来看看class中的静态方法的使用。
class User {
show() {
//给User的实例化对象添加的方法称为普通方法
console.log("prototype.show");
}
static show(){
//给User本身添加的方法称为静态方法
console.log("static.show")
}
}
let hd = new User();
console.log(hd);
User.show();