漂泊雪狼的博客

思考,讨论,分享C#,JavaScript,.NET,Oracle,SQL Server……技术

导航

面向对象javascript编程

Posted on 2016-07-23 17:29  漂泊雪狼  阅读(177)  评论(0编辑  收藏  举报

以构造函数的方式定义对象

 function Person(name, age) {
        this.name = name;
        this.age = age;
        this.sayName = function () {
            alert(this.name);
        }
    }

    var person1 = new Person("wilson1", 10);
    var person2 = new Person("wilson2",20);

    Person("wilson3", 30);

    person1.sayName();
    person2.sayName();

    window.sayName();

 

 

 

定义对象属性

  var person = { _name: "", age: 0, Name: "" };
    Object.defineProperty(person, "name", {
        get: function () {
            return this._name;
        },
        set: function (newvalue) {
            this._name = newvalue;
        }
    });
    
    person.name = "wilson.fu";

 

 原型式定义对象

var Person = function (age, name) {
        this.age = age;
        this.name = name;
    }
    Person.prototype.name = "";
    Person.prototype.age = 0;
    Person.prototype.sayName = function () {
        alert(this.name);
    }
    //Person.prototype.name = "wilson";

    var person1 = new Person(10, "wilson1");
    person1.sayName();

    var person2 = new Person(20, "wilson2");

    person2.sayName();

 构造函数与原型模式结合式声明对象

 

   var Person = function (age, name) {
        this.age = age;
        this.name = name;
    }
    //Person.prototype.name = "Old Value";
    //Person.prototype.age = 0;
    //Person.prototype.sayName = function () {
    //    alert(this.name);
    //}

    Person.prototype = {
        constructor:Person,
        sayName: function () {
            alert(this.name);
        }
    };

 

详见:http://www.cnblogs.com/weiweictgu/p/5658996.html