谈谈对于js面向对象的理解
1、构造函数就是把属性封装在函数里面,如果属性很多却没有用到会增加内存,
所以不要放太多属性,为了减少内存,提高运行速度,就要用到原型prototype
var cat=new Person('mingming',12)
Javascript规定,每一个构造函数都有一个prototype
属性,指向另一个对象。每个实例都会继承,这个对象的属性和方法,
我们把一些不便的属性和方法放在原型里面,它就可以指向同一个内存地址,可以提高运行速度
2、对象之间的继承
构造函数继承 和 prototype原型继承
第一,构造函数继承 只需要在子函数添加 parent.apply(this, arguments); 即可
function Animal(){ this.species = "动物"; } function Cat(name,color){ Parent.apply(this, arguments); this.name = name; this.color = color; }
var cat=new Animal('mingming','红色');
console.log(cat.species);
第二,原型继承
子函数的prototype属性继承Animal实例,那么就实现子函数继承父函数了
function Animal(){ this.species = "动物"; } function Cat(name,color){ this.name = name; this.color = color; } Cat.prototype = new Animal(); Cat.prototype.constructor = Cat; var cat1 = new Cat("大毛","黄色"); alert(cat1.species); // 动物
第三,直接继承
不变的属性都可以直接写入Animal.prototype。所以,我们也可以让Cat()跳过 Animal(),直接继承Animal.prototype。
function Animal(){ } Animal.prototype.species = "动物"; function Cat(name,color){ this.name = name; this.color = color; } Cat.prototype = Animal.prototype; Cat.prototype.constructor = Cat; var cat1 = new Cat("大毛","黄色"); alert(cat1.species); // 动物