2015-05-06 60 views
0

與工廠方法的性質我有一類我試圖與工廠設計模式覆蓋,但沒能做到這一點.. 如何調用它究竟改變對象的屬性如何改變在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"); 

回答

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" 
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