Prototype模式
Javascript规定,每一个构造函数都有一个prototype
属性,指向另一个对象。这个对象的所有属性和方法,都会被构造函数的实例继承。
这意味着,我们可以把那些不变的属性和方法,直接定义在prototype
对象上。
function Cat(name,color){
this.name = name;
this.color = color;
}
Cat.prototype.type = "猫科动物";
Cat.prototype.eat = function(){console.log("吃老鼠")};
然后,生成实例。
let cat1 = new Cat("大毛","黄色");
let cat2 = new Cat("二毛","黑色");
console.log(cat1.type); // 猫科动物
cat1.eat(); // 吃老鼠
这时所有实例的type
属性和eat()
方法,其实都是同一个内存地址,指向prototype
对象,因此就提高了运行效率。
console.log(cat1.eat == cat2.eat); //true