淺談js中的oop

估計不少作前端被面試的同窗總會被問到會不會oop開發,有些人一下矇蔽了,什麼oop。若是面試官說面向對象,或許你一下就明瞭了。前端

這個問題包含幾個細節,es6

  第一個是逼格(😄 )。面試

     第二個是對象。函數

         js中有六種數據類型,包括五種基本數據類型(Number,String,Boolean,Null,Undefined),和一種混合數據類型(Object)。oop

         既然是面向對象,那確定是要有對象的( 😢 );requirejs

        對象既有字面量對象和new 實例化對象;        ui

        

var obj={ name:"weijueye", sayName:function(){ alert("姓名"+this.name+";性別"+this.sex); }, sex:'men' } obj.sayName(); //或者
var obj2={}; obj2.name='weijueye'; obj2.sayNmae=function(){ alert("姓名"+this.name+";性別"+this.sex); } obj2.sex='男'; obj2.sayNmae(); //或者 //1. value:值,默認是undefined

//2. writable:是不是隻讀property,默認是false,有點像C#中的const

//3. enumerable:是否能夠被枚舉(for in),默認false

//4. configurable:是否能夠被刪除,默認false
var obj3={} Object.defineProperties(obj3, { 'name': { value: 'weijueye', writable: true, enumerable: true, configurable: true }, sayName:{ value:function () { alert("姓名"+this.name+";性別"+this.sex); }, writable:false, configurable: false }, 'sex': { value: 'men', writable: false, enumerable: false, configurable: false } }); obj3.sayName(); // 或者利用函數直接返回一個函數
function Person(name,sex) { return { name:name, sayName:function(){ alert("姓名"+this.name+";性別"+this.sex); }, sex:sex } } Person('weijueye','men').sayName(); //實例化對象
function Person(name,sex) { var firstName='liu'; this.name=name; this.sex=sex; } Person.prototype.sayName=function(){ alert("姓名"+this.name+";性別"+this.sex); }; new Person('weijueye','men').sayName(); //在es6中終於能夠用求之不得的類
class Person { //構造函數
 constructor(name,sex){ var firstName='liu'; this.name=firstName+name; this.sex=sex; } //屬性
 sayName(){ setTimeout(()=>{ alert("姓名"+this.name+";性別"+this.sex); }, 1000); } } var person = new Person('weijueye','men') person.sayName();

 

面向對象開發的好處,減小全局變量污染;多人開發適用模塊開發如 CMD下的seajs和AMD下requirejs,this

區別是cmd按需加載(我的推薦)amd是預加載spa

//  AMD:
 define(["./a", "./b"], function(a, b) { //BEGIN
  if (true) { a.doSomething(); } else { b.doSomething(); } //END
}); //  CMD:
 define(function(require) { // BEGIN
  if(some_condition) { require('./a').doSomething(); } else { require('./b').soSomething(); } // END
});
相關文章
相關標籤/搜索