JavaScript构造函数的理解
function meterial(){
console.log("miss you");
}
function product(name,sex){
var obj = {};
obj.name = name;
obj.sex = sex;
obj.meterial = meterial;
return obj;
}
var obj1 = product(张三,男);
种方法让构造器变得像java的类一样妙
function Product(name,sex){
this.name = name;
this.sex = sex;
this.meterial = meterial;
}
var obj2 = new Product(张三,男);
Prototype(原型加继承)
Prototype属性是在对象找不到对应的属性和方法后就会去寻找的地方,换句话说,如果该对象有此属性就会覆盖prototype,如果没有就会像变魔术一样出现,有点继承和多态的感觉了
function Person(name,sex){
this.name = name;
this.sex = sex;
}
Person.prototype.meterial = meterial;
当然最有趣还是要视觉上的封装
function Person(name,sex){
this.name = name;
this.sex = sex;
if(Person._initial = =false)
{
this.merial = merial;
}
Person._initial = true;
}
Es6语法
class Person{
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
|