《中级前端1.11》JavaScript面向对象详解
当代码量过大过多的时候耦合性就会变得极高,这个时候,采用面向对象思想是绝对有必要的!

JS面向对象-认识面向对象

最基本的面向对象:
var person = { name : "wood", age : 30, eat : function(){ alert("能吃"); } } person.height = 100; alert(person.name);
函数构造器构造对象:
function Person(){ } Person.prototype = { name : "wood", age : 26, eat : function(){ alert("我在吃"); } } var p = new Person(); document.write(p.name);
深入JavaScript面向对象
面向对象书写格式:
(function() { var n = "kk"; function People(name) { this._name = name; } People.prototype.say = function() { alert("peo-hello " + this._name); } window.People = People; }()); (function() { function Student(name) { this._name = name; } Student.prototype = new People(); //继承 var superSay = Student.prototype.say; Student.prototype.say = function() { superSay.call(this); //通过call来调用父类方法 alert("stu-hello " + this._name+n); } window.Student = Student; }()); var s = new Student("wood"); s.say();
我的格式:??
function Person(name){ var _name = name; return { sayHello : function(){ alert("Hello"); }, getName : function(){ return _name; }, setName : function(newname){ _name = newname; } } } var p = new Person("wood"); p.sayHello(); document.write(p.getName())
书写格式2:
(function() { var n = "keke"; function Person(name) { var _this = {} _this._name = name; _this.sayHello = function() { alert("PHello" + _this._name+n); } return _this; } window.Person = Person; }()); function Teacher(name) { var _this = Person(name); var superSay = _this.sayHello; _this.sayHello = function() { superSay.call(_this); alert("THello" + _this._name); } return _this; } var t = Teacher("wood"); t.sayHello();

浙公网安备 33010602011771号