搜尋
首頁web前端js教程每天一篇javascript學習小結(物件導向程式設計)_javascript技巧

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;
  }
  
  var person1 = createPerson("Nicholas", 29, "Software Engineer");
  var person2 = createPerson("Greg", 27, "Doctor");
  
  person1.sayName(); //"Nicholas"
  person2.sayName(); //"Greg"

工廠模型的方法的缺點是會產生大量重複程式碼!

2、建構子模式建立物件

 function Person(name, age, job){
   this.name = name;
   this.age = age;
   this.job = job;
   this.sayName = function(){
    alert(this.name);
   }; 
  }
  
  var person1 = new Person("Nicholas", 29, "Software Engineer");
  var person2 = new Person("Greg", 27, "Doctor");
  
  person1.sayName(); //"Nicholas"
  person2.sayName(); //"Greg"
  
  alert(person1 instanceof Object); //true
  alert(person1 instanceof Person); //true
  alert(person2 instanceof Object); //true
  alert(person2 instanceof Person); //true
  
  alert(person1.constructor == Person); //true
  alert(person2.constructor == Person); //true
  
  alert(person1.sayName == person2.sayName); //false  

 使用new關鍵字建立物件會經歷以下四個過程

  • 1、建立一個新物件
  • 2、將建構子的作用域賦給一個新物件(因此this就指向了這個新物件)
  • 3、執行建構子的方法(為這個新物件賦值)
  • 4、回傳新物件

3、將建構子當函數用

 function Person(name, age, job){
   this.name = name;
   this.age = age;
   this.job = job;
   this.sayName = function(){
    alert(this.name);
   };
  }
  
  var person = new Person("Nicholas", 29, "Software Engineer");
  person.sayName(); //"Nicholas"
  
  Person("Greg", 27, "Doctor"); //adds to window
  window.sayName(); //"Greg"
  
  var o = new Object();
  Person.call(o, "Kristen", 25, "Nurse");
  o.sayName(); //"Kristen"

建構函式當做函式使用就和普通的函式沒有任何不同,它屬於window物件下面新增的方法而已。由於構造函數創建的對象實際上是創建一個新對象,因此在本質上兩者還是不一樣的,還是分離的,他們的方法還是不一樣的!

4、將共有的方法方法全域解決不一致的問題

 function Person(name, age, job){
   this.name = name;
   this.age = age;
   this.job = job;
   this.sayName = sayName;
  }
  
  function sayName(){
   alert(this.name);
  }
  
  var person1 = new Person("Nicholas", 29, "Software Engineer");
  var person2 = new Person("Greg", 27, "Doctor");
  
  person1.sayName(); //"Nicholas"
  person2.sayName(); //"Greg"
  
  alert(person1 instanceof Object); //true
  alert(person1 instanceof Person); //true
  alert(person2 instanceof Object); //true
  alert(person2 instanceof Person); //true
  
  alert(person1.constructor == Person); //true
  alert(person2.constructor == Person); //true
  
  alert(person1.sayName == person2.sayName); //true  

雖然上面的方法解決了一致的問題,但是定義的全局的方法本身屬於window,那麼局部和全局就沒有分開!所以這個方法使用的並不多見!也不建議使用。

5、原型模式

我們創建的任何的一個函數都有一個原型對象,這個屬性是一個指針,它指向一個對象,而這個對象的作用是可以有特定的類型的所有的實例共享的方法!

 function Person(){
  }
  
  Person.prototype.name = "Nicholas";
  Person.prototype.age = 29;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function(){
   alert(this.name);
  };
  
  var person1 = new Person();
  person1.sayName(); //"Nicholas"
  
  var person2 = new Person();
  person2.sayName(); //"Nicholas"
  
  alert(person1.sayName == person2.sayName); //true
  
  alert(Person.prototype.isPrototypeOf(person1)); //true
  alert(Person.prototype.isPrototypeOf(person2)); //true
  
  //only works if Object.getPrototypeOf() is available
  if (Object.getPrototypeOf){
   alert(Object.getPrototypeOf(person1) == Person.prototype); //true
   alert(Object.getPrototypeOf(person1).name); //"Nicholas"
  }

理解原型

無論何時只要是建立了一個函數,就會建立一個原型屬性,這個屬性指向函數的原型物件。在預設的情況下,原型物件都會包含一個constructor(建構函式屬性),這個屬性包含一個指向prototype屬性所在函數的指標!

屬性讀取的順序

每當程式碼讀取某個物件的屬性時候,都會執行一次搜索,目標是具有給定名字的屬性,搜尋從物件的實例本身開始查找,如有則返回,沒有則繼續搜尋該物件的原型鏈,直到搜尋到原型鏈的最外層!

 function Person(){
  }
  
  Person.prototype.name = "Nicholas";
  Person.prototype.age = 29;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function(){
   alert(this.name);
  };
  
  var person1 = new Person();
  var person2 = new Person();
  
  person1.name = "Greg";
  alert(person1.name); //"Greg" 来自实例
  alert(person2.name); //"Nicholas" 来自原型

如果刪除了這個元素的實例屬性

function Person(){
  }
  
  Person.prototype.name = "Nicholas";
  Person.prototype.age = 29;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function(){
   alert(this.name);
  };
  
  var person1 = new Person();
  var person2 = new Person();
  
  person1.name = "Greg";
  alert(person1.name); //"Greg" ?from instance
  alert(person2.name); //"Nicholas" ?from prototype
  
  delete person1.name;
  alert(person1.name); //"Nicholas" - from the prototype

6、hasOwnProperty方法

這個方法可以偵測一個屬性是否存在於實例中,還是存在於原型中! hasOwnProperty是從Object繼承來的,只要給定屬性存在於物件實例中,才會回傳true.

 function Person(){
    }
    
    Person.prototype.name = "Nicholas";
    Person.prototype.age = 29;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function(){
      alert(this.name);
    };
    
    var person1 = new Person();
    var person2 = new Person();
    
    alert(person1.hasOwnProperty("name")); //false
    alert("name" in person1); //true
    
    person1.name = "Greg";
    alert(person1.name);  //"Greg" ?from instance
    alert(person1.hasOwnProperty("name")); //true
    alert("name" in person1); //true
    
    alert(person2.name);  //"Nicholas" ?from prototype
    alert(person2.hasOwnProperty("name")); //false
    alert("name" in person2); //true
    
    delete person1.name;
    alert(person1.name);  //"Nicholas" - from the prototype
    alert(person1.hasOwnProperty("name")); //false
    alert("name" in person1); //true

7、Object.keys() 可列舉屬性方法

這個方法接收一個物件作為參數,傳回一個包含所有可枚舉屬性的字串陣列

 function Person(){
    }
    
    Person.prototype.name = "Nicholas";
    Person.prototype.age = 29;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function(){
      alert(this.name);
    };
    
    var keys = Object.keys(Person.prototype);
    alert(keys);  //"name,age,job,sayName"
如果想得到所有实例的属性,无论它是否可以枚举都可以使用这个方法来获取
 function Person(){
    }
    
    Person.prototype.name = "Nicholas";
    Person.prototype.age = 29;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function(){
      alert(this.name);
    };
    
    var keys = Object.getOwnPropertyNames(Person.prototype);
    alert(keys);  //"constructor,name,age,job,sayName"

此方法高版瀏覽器才支援

8、簡單的原型寫法

 function Person(){
    }
    
    Person.prototype = {
      name : "Nicholas",
      age : 29,
      job: "Software Engineer",
      sayName : function () {
        alert(this.name);
      }
    };

    var friend = new Person();
    
    alert(friend instanceof Object); //true
    alert(friend instanceof Person); //true
    alert(friend.constructor == Person); //false
    alert(friend.constructor == Object); //true

重寫了原型就等於將預設的原型方法覆蓋,那麼同樣的建構方法也會被重寫,而重寫的建構方法指向了Object物件!而不是原來的物件Person

如果還是想指向先前的建構方法,可以顯示的指定

 function Person(){
    }
    
    Person.prototype = {
      constructor : Person,
      name : "Nicholas",
      age : 29,
      job: "Software Engineer",
      sayName : function () {
        alert(this.name);
      }
    };

    var friend = new Person();
    
    alert(friend instanceof Object); //true
    alert(friend instanceof Person); //true
    alert(friend.constructor == Person); //true
    alert(friend.constructor == Object); //false

9、原型方法的動態添加

function Person(){
    }
    
    Person.prototype = {
      constructor: Person,
      name : "Nicholas",
      age : 29,
      job : "Software Engineer",
      sayName : function () {
        alert(this.name);
      }
    };
    
    var friend = new Person();
    
    Person.prototype.sayHi = function(){
      alert("hi");
    };
    
    friend.sayHi();  //"hi" ?works!

10、原生物件的原型方法

alert(typeof Array.prototype.sort);     //"function"
    alert(typeof String.prototype.substring);  //"function"

    String.prototype.startsWith = function (text) {//修改原生对象的原型方法
      return this.indexOf(text) == 0;
    };
    
    var msg = "Hello world!";
    alert(msg.startsWith("Hello"));  //true

11、組合使用建構子和原型模式建立物件

//构造函数模式
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); //true

12、動態原型模式

function Person(name, age, job){
    
      //properties
      this.name = name;
      this.age = age;
      this.job = job;
      
      //methods
      if (typeof this.sayName != "function"){
      
        Person.prototype.sayName = function(){
          alert(this.name);
        };
        
      }
    }

    var friend = new Person("Nicholas", 29, "Software Engineer");
    friend.sayName();

13、寄生建構子模式

 function Person(name, age, job){
var o = new Object();//依赖全局对象初始化一个对象,然后再返回这个对象
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
}; 
return o;
}

var friend = new Person("Nicholas", 29, "Software Engineer");
friend.sayName(); //"Nicholas"

function SpecialArray(){ 

//create the array
var values = new Array();

//add the values
values.push.apply(values, arguments);

//assign the method
values.toPipedString = function(){
return this.join("|");
};

//return it
return values; 
}

var colors = new SpecialArray("red", "blue", "green");
alert(colors.toPipedString()); //"red|blue|green"

alert(colors instanceof SpecialArray);

上訴方法有一點說明下,由於它是依賴外層對象來創建一個新對象,因此不能依賴 instanceof方法來確定屬性和方法的來源!它實際上和建構函數的沒有關係!

14、穩健建構子模式

 function Person(name, age, job){
      var o = new Object();
      o.sayName = function(){
        alert(name);
      };  
      return o;
    }
    
    var friend = Person("Nicholas", 29, "Software Engineer");
    friend.sayName(); //"Nicholas"

此方法不依賴任何new this 關鍵符!如果要存取物件的方法和屬性,只能透過物件已經定義好的方法來取得!

15、繼承
javascript實作繼承是透過原型鏈來實現的

function SuperType(){
      this.property = true;//定义一个属性
    }
    
    SuperType.prototype.getSuperValue = function(){//定义的原型方法
      return this.property;
    };
    
    function SubType(){
      this.subproperty = false;
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();
    
    SubType.prototype.getSubValue = function (){
      return this.subproperty;
    };
    
    var instance = new SubType();
    alert(instance.getSuperValue());  //true
    
    alert(instance instanceof Object);   //true
    alert(instance instanceof SuperType);  //true
    alert(instance instanceof SubType);   //true

    alert(Object.prototype.isPrototypeOf(instance));  //true
    alert(SuperType.prototype.isPrototypeOf(instance)); //true
    alert(SubType.prototype.isPrototypeOf(instance));  //true
SubType继承SuperType的方法和属性,因此当instance可以直接调用SuperType的方法!
 function SuperType(){
      this.property = true;
    }
    
    SuperType.prototype.getSuperValue = function(){
      return this.property;
    };
    
    function SubType(){
      this.subproperty = false;
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();
    
    //new method
    SubType.prototype.getSubValue = function (){
      return this.subproperty;
    };
    
    //override existing method
    SubType.prototype.getSuperValue = function (){
      return false;
    };
    
    var instance = new SubType();
    alert(instance.getSuperValue());  //false

上面的例子說明,重寫的原型會覆蓋先前繼承的原型,最後返回的往往不是預期的效果

 function SuperType(){
      this.property = true;
    }
    
    SuperType.prototype.getSuperValue = function(){
      return this.property;
    };
    
    function SubType(){
      this.subproperty = false;
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();
    
    //使用字面量添加的方法导致上面的方法失效了
    SubType.prototype = {
      getSubValue : function (){
        return this.subproperty;
      },
    
      someOtherMethod : function (){
        return false;
      }
    }; 
    
    var instance = new SubType();
    console.log(instance);
    alert(instance.getSuperValue());  //error!

下面的例子也說明重寫原型帶來的風險

 function SuperType(){
      this.colors = ["red", "blue", "green"];
    }

    function SubType(){      
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();

    var instance1 = new SubType();
    instance1.colors.push("black");
    alert(instance1.colors);  //"red,blue,green,black"
    
    var instance2 = new SubType();
    alert(instance2.colors);  //"red,blue,green,black"

原型共享导致两个不同的对象调用的同一个数据
16、借用构造函数来实现继承

 function SuperType(){
      this.colors = ["red", "blue", "green"];
    }

    function SubType(){ 
      //inherit from SuperType
      SuperType.call(this);
    }

    var instance1 = new SubType();
    instance1.colors.push("black");
    alert(instance1.colors);  //"red,blue,green,black"
    
    var instance2 = new SubType();
    alert(instance2.colors);  //"red,blue,green"

传递参数

 function SuperType(name){
      this.name = name;
    }

    function SubType(){ 
      //inherit from SuperType passing in an argument
      SuperType.call(this, "Nicholas");
      
      //instance property
      this.age = 29;
    }

    var instance = new SubType();
    alert(instance.name);  //"Nicholas";
    alert(instance.age);   //29

17、组合继承方式

function SuperType(name){
      this.name = name;
      this.colors = ["red", "blue", "green"];
    }
    
    SuperType.prototype.sayName = function(){
      alert(this.name);
    };

    function SubType(name, age){ 
      SuperType.call(this, name);
      
      this.age = age;
    }

18、原型继承

 function object(o){
      function F(){}
      F.prototype = o;
      return new F();
    }
    
    var person = {
      name: "Nicholas",
      friends: ["Shelby", "Court", "Van"]
    };
    
    var anotherPerson = object(person);
    anotherPerson.name = "Greg";
    anotherPerson.friends.push("Rob");

19、寄生组合式继承

 function object(o){
      function F(){}
      F.prototype = o;
      return new F();
    }
  
    function inheritPrototype(subType, superType){
      var prototype = object(superType.prototype);  //create object
      prototype.constructor = subType;        //augment object
      subType.prototype = prototype;         //assign object
    }
                
    function SuperType(name){
      this.name = name;
      this.colors = ["red", "blue", "green"];
    }
    
    SuperType.prototype.sayName = function(){
      alert(this.name);
    };

    function SubType(name, age){ 
      SuperType.call(this, name);
      
      this.age = age;
    }

    inheritPrototype(SubType, SuperType);
    
    SubType.prototype.sayAge = function(){
      alert(this.age);
    };
    
    var instance1 = new SubType("Nicholas", 29);
    instance1.colors.push("black");
    alert(instance1.colors); //"red,blue,green,black"
    instance1.sayName();   //"Nicholas";
    instance1.sayAge();    //29
    
    
    var instance2 = new SubType("Greg", 27);
    alert(instance2.colors); //"red,blue,green"
    instance2.sayName();   //"Greg";
    instance2.sayAge();    //27

以上就是今天的javascript学习小结,之后每天还会继续更新,希望大家继续关注。

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript的角色:使網絡交互和動態JavaScript的角色:使網絡交互和動態Apr 24, 2025 am 12:12 AM

JavaScript是現代網站的核心,因為它增強了網頁的交互性和動態性。 1)它允許在不刷新頁面的情況下改變內容,2)通過DOMAPI操作網頁,3)支持複雜的交互效果如動畫和拖放,4)優化性能和最佳實踐提高用戶體驗。

C和JavaScript:連接解釋C和JavaScript:連接解釋Apr 23, 2025 am 12:07 AM

C 和JavaScript通過WebAssembly實現互操作性。 1)C 代碼編譯成WebAssembly模塊,引入到JavaScript環境中,增強計算能力。 2)在遊戲開發中,C 處理物理引擎和圖形渲染,JavaScript負責遊戲邏輯和用戶界面。

從網站到應用程序:JavaScript的不同應用從網站到應用程序:JavaScript的不同應用Apr 22, 2025 am 12:02 AM

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python vs. JavaScript:比較用例和應用程序Python vs. JavaScript:比較用例和應用程序Apr 21, 2025 am 12:01 AM

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

C/C在JavaScript口譯員和編譯器中的作用C/C在JavaScript口譯員和編譯器中的作用Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在行動中:現實世界中的示例和項目JavaScript在行動中:現實世界中的示例和項目Apr 19, 2025 am 12:13 AM

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

JavaScript和Web:核心功能和用例JavaScript和Web:核心功能和用例Apr 18, 2025 am 12:19 AM

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

了解JavaScript引擎:實施詳細信息了解JavaScript引擎:實施詳細信息Apr 17, 2025 am 12:05 AM

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境