构造函数(首字母要大写)
构造函数this指向创创建出的对象或实例
function Chess(name, color, x, y) { //这里定义了一个名为Chess的构造函数
this.name = name
this.color = color
this.position = {}
this.position.x = x
this.position.y = y
this.move = function (x, y) {
console.log(this.color + this.name + '移动到了' + x + '-' + y);
this.position.x = x
this.position.y = y
}
}
let a = new Chess('马', '红', 1, 2)
a.move()
console.log(a.move);
let b = new Chess('车', '黑', 4, 6)
let c = new Chess('象', '黑', 5, 9)
console.log(a);
console.log(b);
console.log(c);
构造函数的作用就是为了每次要创建一个新的对象,并且这个对象跟前一个对象有相同的属性时,就不用再重复的写相同的代码了,直接用构造函数来创建就可以,只需要每次将值通过构造函数传进去就可以。