Javascript面向对象谈
一:创建对象:
//对象封装原始模式 var Cat = { name: '', color: '', eat: function () { } }; function eat() { console.log("test"); } var cat1 = { name: "binfire", color: "red", eat: eat };
二:构建类:
//对象封装 function Cat(name, color) { this.name = name; this.color = color; this.eat = function () { console.log('eat fish'); }; } var cat = new Cat("binfire", "red"); cat.eat();
三:Prototype
//js扩展方法和属性 function Cat(name, color) { this.name = name; this.color = color; } Cat.prototype.type = "mammal"; Cat.prototype.eat = function () { console.log("fk"); }
四:Call/Apply继承
function Animal() { this.species = 'animal'; this.sleep = function () { console.log('I\'m sleep at night'); }; } //通过cat对象调用Animal /** @class Cat*/ function Cat(name, color) { Animal.apply(this); this.name = name; this.color = color; } var cat1 = new Cat("binfire", "red"); cat1.sleep();
五:原型链原理
var Person = function () { }; Person.prototype.Say = function () { console.log("person say"); }; var p = new Person(); console.log(p.__proto__ == Person.prototype); //p没有Say方法,于是去_proto中找,也就是Person.propotype, //Person.propotype.Say p.Say();
1.var p={}; 初始化一个对象p
2.p.__proto__=Person.propotype;
3.Person.call(p); 构造p,初始化p
function Animal() { this.species = 'animal'; this.sleep = function () { console.log('I\'m sleeping'); }; } function Cat(name, color) { this.name = name; this.color = color; } Cat.prototype = new Animal(); Cat.prototype.eat = function () { console.log("eating") }; var cat = new Cat("binfire", "red"); cat.sleep();