var dog = new Animal('wangwang','boy'); var cat = new Animal('miaomiao','girl'); console.log(dog.common===cat.common); // false
为了解决构造函数的对象实例之间无法共享属性的缺点,js提供了prototype属性。 如下代码:
1 2 3 4 5 6 7 8 9 10
function Animal(name,sex){ this.name = name; this.sex = sex; } Animal.prototype.common=function(){ return "cannot speaking" } var dog = new Animal('wangwang','boy'); var cat = new Animal('miaomiao','girl'); console.log(dog.common===cat.common); // true