构造函数简单代码

106 阅读1分钟

es5使用方法:

function Person(name,age,sex){
	this.name = name;
	this.age = age;
	this.sex = sex;
}
var p1 = new Person('lily',13,'女')
// console.log(p1)


function Person2() {
	this.age = 28;
	return 50;
}

var p2 = new Person2();
// console.log(p2.age);   // 28

function Person3(name,age,sex){
	this.name = name;
	this.age = age;
	this.sex = sex;
}
Person3.prototype.say = function (word){
	return (this.name + ' say:'+word)
}
console.log(Person3)
var p31 = new Person3('lily',13,'女')
console.log(p31)
console.log(p31.say('I like eat'))

es6简单使用:

// constructor方法是类的构造函数的默认方法,通过new命令生成对象实例时,自动调用该方法
class Person{
	say(name){
		console.log('my name is'+ name);
		return name;
	}
	constructor(a,b){
		this.a = a;
		this.b = b;
	}
	add(){
		return this.a + this.b;
	}
}
let p1 = new Person(1,2);
console.log(p1)
p1.say('lilei')

// 通过prototype属性对类添加方法
Person.prototype.done = function(word){
	console.log('我喜欢'+word)
}
p1.done('运动')

// 还可以通过Object.assign方法来为对象动态增加方法
Object.assign(Person.prototype,{
	getA: function(){
		console.log('this.a:::'+this.a)
	},
	getB: function(){
		console.log('this.B:::'+this.b)
	}
})
p1.getA()