js面向對象-動態原型模式

動態原型模式(不能使用對象字面量重寫原型)

把全部信息封裝到構造函數中,經過檢查某個應該存在的方法是否有效,來決定是否初始化原型。函數

function Person(name, age, job) {
    //屬性
    this.name = name;
    this.age = age;
    this.job = job;
    // 方法
    if (typeof this.whatJob != "function") {
        Person.prototype.whatJob = function () {
            alert(this.job);
        };
    }
}
var friend = new Person("wheeler", 25, "Software Engineer");
friend.whatJob();
相關文章
相關標籤/搜索