JavaScript -- 面向对象的简单分析

// 第一种:直接赋值:
//var person = {
//    name:"iwen",
//    age:"30",
//    eat:function(){
//        alert("能吃")
//    }
//}
//alert(person.name);

// 使用原型为对象赋值
function Person(){

}
Person.prototype = {
    name:"iwen",
    age:"30",
    eat:function(){
        alert("我在吃")
    }
}

var p = new Person();
alert(p.eat);


//------------第二类--------------//
// 对象之间的调用
/*
function People(name){
    this._name = name;

}
People.prototype.say = function(){
    alert("hello,"+this._name);
}

function Student(name){
    this.name = name;
}

Student.prototype = new People("iwen");


var superSay = Student.prototype.say;

Student.prototype.say = function(){
    superSay.call(this);
    alert("stu-hello");
}

var s = new Student("iwen");
s.say()
 */

//------ 上述可以改写为:(将对象属性封装为私有属性)
(function(){
    var n = "ime"
    function People(name){
        this._name = name;
    }
    People.prototype.say = function(){
        alert("peo-hello,"+this._name+n);
    }
    window.People = People;   // 如果想让外界使用,就让他赋给window
}());

(function(){
    function Student(name){
        this._name = name;
    }
    Student.prototype = new People();
    var superSay = Student.prototype.say;
    Student.prototype.say = function(){
        superSay.call(this);
        alert("stu-hello,"+this._name);
    }
    window.Student = Student;
}());
var s = new Student("iwen");
s.say()


// ------------第三类--------------- //


/*
// 无参数的赋值
//  全部通过对象赋值的操作
function Person(){
    var _this = {}
    _this.sayHello = function(){
        alert("hello");
    }
    return _this;
}

function Teacher(){
    var _this = Person();
    var superSay = _this.sayHello();
    _this.sayHello = function(){
        alert("Thello");
    }
    return _this;
}

var t = Teacher();
t.sayHello();
*/


//-------以上是无参数,下面是有参数类型的------//

// 写完后,可以尝试将第一个函数块封装起来,对比一下使用区别
(function(){
    var n = "Tom";
    function Person(name){
        var _this = {}
        _this._name = name;
        _this.sayHello = function(){
            alert("hello,"+this._name+  n);
        }
        return _this;
    }
    window.Person = Person;
}())


function Teacher(name){
    var _this = Person(name);
    var superSay = _this.sayHello();
    _this.sayHello = function(){
        alert("Thello"+this._name);
    }
    return _this;
}

var t = Teacher("iwen");
t.sayHello();

可以发现,对于初学者,最后一种是最容易理解与学习的,需要注意的是,在有参的时候,需要现将参数提取出来,再进行使用;

猜你喜欢

转载自blog.csdn.net/RedGuy_anluo/article/details/51316068