- 构造函数
- 成员函数
- prototype
小明 --> 人的实例
属性: 身高 体重 ...
行为: 吃饭 睡觉 唱歌 ...
成员函数就是用来描述对象的行为的
①每个Person类的实例, 都会有各自的 eat() sleep() 函数代码
对实例属性和方法的改变, 不会影响到其他的实例.
但, 这会造成内存的额外消耗. 如图
![](https://img-blog.csdn.net/20131112130854562?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd3VxaW5mZWlfY3M=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
②可以使用 "==", 判断对象的方法的地址是否相等
③可使用原型的方式来使每个实例共享函数代码.
function Person() {
}
prototype, 相当于Java的static,
修饰的属性/方法是属于类的.
- 成员函数
- prototype
1. 成员函数 的介绍
小明 --> 人的实例
属性: 身高 体重 ...
行为: 吃饭 睡觉 唱歌 ...
成员函数就是用来描述对象的行为的
2. 构造函数 -- 描述 小明
function Person(name, height, weight) {
this.name = name;
this.height = height;
this.weight = weight;
this.show = function() {
return this.name + " " + this.height + " " + this.weight;
}
this.eat = function(food) {
return this.name + " is eating " + food;
}
this.sleep = function() {
return this.name + " like sleeping!";
}
this.sing = function(song) {
return this.name + " like singing " + song;
}
}
var p = new Person("小明", "170cm", "50kg");
console.info( p.show() );
console.info( p.eat( "apple" ) );
console.info( p.sleep() );
console.info( p.sing( "哇哈哈" ) );
3. 注
①每个Person类的实例, 都会有各自的 eat() sleep() 函数代码
对实例属性和方法的改变, 不会影响到其他的实例.
但, 这会造成内存的额外消耗. 如图
②可以使用 "==", 判断对象的方法的地址是否相等
③可使用原型的方式来使每个实例共享函数代码.
4. 给单独对象追加方法
function Person() {
}
1) 方式一
function func() {
// do something
}
var p = new Person();
p.show = func;
2) 方式二
var p = new Person();
p.show = function() {
// do something
};
3) 对象间互不影响
function Person() {
this.name = "123";
}
var p1 = new Person();
var p2 = new Person();
console.info( p1.name ); // 123
console.info( p2.name ); // 123
p1.name = "AAA";
console.info( p1.name ); // AAA
console.info( p2.name ); // 123
var p3 = new Person();
console.info( p3.name ); // 123
5. 让所有对象共享同一个函数 -- prototype
1) 说明
prototype, 相当于Java的static,
修饰的属性/方法是属于类的.
2) 语法
ClassName.prototype.propertyName = propertyValue;
ClassName.prototype.methodName = method;3) 举例
function Dog() {
this.eat = function() {
return "a dog is eating!";
};
Dog.prototype.bark = function() {
return "a dog is singing!!!";
};
}
var d1 = new Dog();
var d2 = new Dog();
console.info( d1.eat == d2.eat ); // false
console.info( d1.bark == d2.bark ); // true
console.info( d1.bark() );
console.info( d2.bark() );
// 更改模板
Dog.prototype.bark = function() {
return "heihei, I'm a Cat!!!!!!"
}
console.info( d1.bark() );
console.info( d2.bark() );
// false
// true
// a dog is singing!!!
// a dog is singing!!!
// heihei, I'm a Cat!!!!!!
// heihei, I'm a Cat!!!!!!