JAVA全系列 教程
3762个小节阅读:7094.3k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
通过类的实例对象调用方法
xxxxxxxxxx
class People{
say(){
console.log("Hello");
}
}
var p = new People();
p.say()
实例属性指的是类的实例对象可调用的属性
xxxxxxxxxx
class People{
constructor(name,age){
this.name = name;
this.age = age;
}
say(){
console.log(this.name,this.age);
}
}
var p = new People("iwen",20);
p.say()
console.log(p.name,p.age);
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static
关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”
xxxxxxxxxx
class Person {
static classMethod() {
console.log("Hello");
}
}
Person.classMethod() // Hello
var p = new Person();
p.classMethod() // p.classMethod is not a function
温馨提示
注意,如果静态方法包含
this
关键字,这个this
指的是类,而不是实例。
xxxxxxxxxx
class People {
static getSay() {
this.say();
}
static say() {
console.log('hello');
}
say() {
console.log('world');
}
}
People.getSay() // hello
静态属性指的是 Class 本身的属性,即Class.propName
xxxxxxxxxx
class People{}
People.status = "等待"
console.log(People.status);
实时效果反馈
1. 下列代码,运行结果是什么:
xxxxxxxxxx
class People {
static getSay() {
this.say();
}
static say() {
console.log('hello');
}
say() {
console.log('world');
}
}
People.getSay()
A hello
B world
C null
D undefined
答案
1=>A