Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

构造函数添加方法,为什么必须用.prototype往原型上添加方法,实例才能调用,否则undefined

可能我过于较真

function Student(name, age, sex) {
  this.name = name
  this.age = age
  this.sex = sex
}

Student.sayHi = function () {
  console.log('大家好 我是' + this.name)
}

Student.test = 'abc'

构造函数Student也是对象,为什么不能通过.sayHi直接添加方法呢?无论添加属性还是方法都添加不上

console.log('Student', Student);

Student ? Student(name, age, sex) {
this.name = name
this.age = age
this.sex = sex
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

学过 Java / C# / Golang 一类的 OOP 强类型语言吗?

这就是基本的静态方法和类方法的区别。

P.S. C# 3.0 后增加了可以在实例里访问静态方法的特性,但本质是个语法糖。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...