动态原型模式

//把构造函数模式与原型模式结合,所有信息都封装在了构造函数中,即在构造函数中初始化原型:
function Person(name, age, job) {
    //实例属性
    this.name = name;
    this.age = age;
    this.job = job;

    //原型方法,这里只执行一次!---因为在构造函数中定义成员会首先从原型中查找,请看下面示例1。
    if (typeof this.say != "function") {
        alert("我只执行一次。");
        Person.prototype.say = function () {
            document.write("Hello,I'm " + this.name + "," + this.age + " years old,i'm a " + this.job+"。<br/>");
        }
    }
}

var person1 = new Person("wede", 29, "SoftWare");
var person2 = new Person("kitty", 18, "Student");
person1.say();
person2.say();

/*************************************** 示例1 *****************************************************/

function Family() {
    //这里调用this的时候,会检测作用域内的所有成员,包括原型中的成员,所以在原型中添加的成员会反映到this作用域中。
    this.father = "hahh.";
}
Family.prototype.father = "father."; //在原型中的定义优先于在构造函数中定义。
var family = new Family();
document.write(family.father); //hahh.

posted @ 2018-10-08 15:02  skybirdzw  阅读(962)  评论(0编辑  收藏  举报