It has been 1485 days since the last update, the content of the article may be outdated.

原型 prototype

javascript
var Student={
name:'robort',
height:1.2,
run:function(){
return console.log(this.name+" is running...");
}
}

var xm=Object.create(Student);
xm.name='xiaoming'


xm.name//"xiaoming"
xm.run()//"xiaoming is running..."
xm.height//1.2
xm.__proto__===Student; //true

构造prototype

除了直接用{ … }创建一个对象外,JavaScript还可以用一种构造函数的方法来创建对象。
它的用法是,先定义一个构造函数:

javascript
function Student(name,age){
this.name=name;
this.age=age;
this.hello=function(){
alert("hello "+this.name+" you are "+this.age);
};
}

//用关键字new来调用这个函数,并返回一个对象:

var xm=new Student('xiaoming',18);
xm.name;//"xiaomming"
xm.hello();//"hello xiaoming you are 18"

xm instanceof Student; // true

注意,如果不写new,这就是一个普通函数,它返回undefined。但是,如果写了new,它就变成了一个构造函数,它绑定的this指向新创建的对象,并默认返回this,也就是说,不需要在最后写return this;。

类似于python 的构造方法:

python
class Student():
def __init__(self,name,age):
self.name=name
self.age=age
def hello(self):
print("hello "+self.name+" you are ",self.age)

xm=Student('xiaoming',18)
print(xm.hello())

共享方法

如果我们通过new Student()创建了很多对象,这些对象的hello函数实际上只需要共享同一个函数就可以了,这样可以节省很多内存。

要让创建的对象共享一个hello函数,根据对象的属性查找原则,我们只要把hello函数移动到xiaoming、xiaohong这些对象共同的原型上就可以了,也就是Student.prototype:

javascript
function Student(name) {
this.name = name;
}

Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
};