如何在javascript中使用工厂方法更改属性

时间:2015-05-06 14:12:30

标签: javascript

我有一个班级我试图用工厂设计模式覆盖它但不能这样做..  如何完全调用它来改变对象的属性

function othername() {
var newobj = new Object();
    newobj.fname = "sachin",
         newobj.lname = "rawal",
             newobj.fullname = function () {
             alert(this.fname);
             }
             return newobj
}

var othername1 = othername ("hi","hello");

2 个答案:

答案 0 :(得分:0)

使用原型你可以做到。

function othername() {
var newobj = new Object();
    newobj.fname = "sachin",
         newobj.lname = "rawal",
             newobj.fullname = function () {
             alert(this.fname);
             }
             return newobj
}

var othername1 = othername ("hi","hello");

原型:

othername.prototype.middleName = "middleNameString";

var named = othername();
var md = named.middleName // md == "middleNameString"

答案 1 :(得分:0)

function Othername(fname,lname) {
    this.fname = fname || "sachin";
    this.lname = lname || "rawal";
};
Othername.prototype.fullname = function (){
    alert(this.fname + " " + this.lname);
};

var othernameDefault = new Othername (); //sachin rawal
var othername1 = new Othername ("hi","hello"); //hi hello