1. 程式人生 > 資訊 >矽谷提出租賃機器人新方案:幫小型工廠一年節省數萬美元

矽谷提出租賃機器人新方案:幫小型工廠一年節省數萬美元

建立物件

工廠模式

function createPerson(name, age, job){
    var o = new Object();
    o.name = name;
    o.age = age;
    o.job = job;
    o.sayName = function(){
        alert(this.name);
    };
    return o;
}

建構函式模式

  • 沒有顯示建立物件
  • 直接將屬性和方法賦給了this物件
  • 沒有return語句
function Person(name, age, job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = function(){
    	alert(this.name);
    };
}

Prototype原型

組合使用建構函式模式和原型模式


function Person(name, age, job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.friends = ["Shelby","court"];
}

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

var person1 = new Person("Nicholas",29,"Software Engineer");
var person2 = new Person("Greg",27,"Doctor");

person1.friends.push("Van");
alert(person1.friends);//"Shelby","court","Van"
alert(person2.friends);//"Shelby","court",
alert(person1.friends === person2.friends);//false  ===全等 判斷引用 ==等於 判斷值
alert(person1.sayName === person2.sayName);//ture

動態原型模式