JavaScript学习笔记-prototype
It has been 1485 days since the last update, the content of the article may be outdated.
原型 prototype
javascript
var Student={ |
构造prototype
除了直接用{ … }创建一个对象外,JavaScript还可以用一种构造函数的方法来创建对象。
它的用法是,先定义一个构造函数:
javascript
function Student(name,age){ |
注意,如果不写new
,这就是一个普通函数,它返回undefined
。但是,如果写了new
,它就变成了一个构造函数,它绑定的this
指向新创建的对象,并默认返回this
,也就是说,不需要在最后写return this
;。
类似于python
的构造方法:
python
class Student(): |
共享方法
如果我们通过new Student()创建了很多对象,这些对象的hello函数实际上只需要共享同一个函数就可以了,这样可以节省很多内存。
要让创建的对象共享一个hello函数,根据对象的属性查找原则,我们只要把hello函数移动到xiaoming、xiaohong这些对象共同的原型上就可以了,也就是Student.prototype:
javascript
function Student(name) { |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment