JS 中 类和实例 的创建 和简单原型

利用函数的思想

function create(name, sex, age){
	var obj = new Object();
	obj.name  = name;
	obj.sex = sex;
	obj.age = age;
    obj.say = function(){
		document.write('hello');
	}
	return obj;
}

var p1 = create('shuang', 'woman', 20);

构造函数法(常用)

function Person(name, age, sex){
	this.name = name;
	this.age = age;
	this.sex = sex;
	this.say = function(){
		document.write('hello');
	}
}

var p1 = new Person('ao', 21, 'man');

简单原型

function Person() {

}
Person.prototype = {
	name : 'zs',
	age : 20,
	job : 'doctor',
	say : function () {
		document.write( 'wo shi yuanxing ' );
	}
};
// 三个参数。 参数1: 重设构造器的对象 参数2:设置属性  参数3 :options配置项
Object.defineProperty( Person.prototype, 'construction', {
	enumerable : false,
	value : Person
});
var p = new Person();
document.write( p.name );
p.say();

猜你喜欢

转载自blog.csdn.net/error311/article/details/88576970