>  기사  >  웹 프론트엔드  >  자바스크립트 객체지향-캡슐화

자바스크립트 객체지향-캡슐화

高洛峰
高洛峰원래의
2017-01-04 09:14:20793검색

1단계: "휴대폰 클래스" 만들기

var MobilePhone = (function(){
    …………
})()

2단계: 이 클래스를 고려하고 여기에 필요한 비공개 속성이 무엇인지 고려하세요. 여기서 정의하고 싶은 것은 인스턴스에서 나오는 휴대폰의 수입니다.

var MobilePhone = (function(){
 //私有属性
 var count = 0; //代表手机的数量
})()

이 예에서 속성 및 메소드의 초기화와 같은 객체의 초기화는 각 휴대폰이 갖게 됩니다. color, size, price 속성도 클로저이므로 count에 접근할 수 있고, count의 값은 (참조가 있는 한) 메모리에 오랫동안 저장됩니다. 🎜>

4단계: 일반적인 메서드:

즉, 인스턴스화되는 모든 휴대폰 객체에서 사용할 수 있는 메서드입니다. 여기서 휴대폰은 다음을 수행할 수 있어야 합니다. 가격, 색상, 사이즈를 변경하고 사이즈, 색상, 가격도 표시합니다.
var MobilePhone = (function(){
 //私有属性
 var count = 0; //代表手机的数量 
     //构造函数
     var creatphone = function(color,size,price){
         count++;
         this._color = color; //手机的颜色
         this._size = size; //手机的大小
         this._price = price; //手机的价格
         this.index = count; //手机索引,是第几台创建的手机手象
      }
})()

여기서 공통 메서드는 "프로토타입 개체"에 배치되어야 합니다.

1. 이 생성자에 의해 인스턴스화된 모든 개체, 즉 생성된 휴대폰은 "프로토타입 개체"를 사용할 수 있습니다. 방법.

2. 생성자에 배치하면 휴대폰 개체가 인스턴스화될 때마다 여러 개의 반복 메서드가 생성되어 메모리를 차지합니다.

3. "constructor":creatphone 설명:

creatphone.prototype ={...}이 이전 프로토타입 객체에 대한 참조를 상당히 덮어쓰기 때문입니다. 프로토타입 객체를 생성자와 연결하기 위해 "constructor":creatphone 속성이 설정됩니다.

5단계: 권한 있는 메서드, 즉 , 클래스의 개인 변수에 액세스할 수 있는 메서드가 필요합니다. 인스턴스에서 얼마나 많은 휴대폰 객체가 나오는지
var MobilePhone = (function(){
 //私有属性
 var count = 0;//代表手机的数量
    //构造函数
     var creatphone = function(color,size,price){
        count++;
        this._color = color; //手机的颜色
        this._size = size; //手机的大小
        this._price = price; //手机的价格
        this.index = count; //手机索引,是第几台创建的手机手象
      }
 //公有方法,存放在原型对象中
 creatphone.prototype = {
      "constructor":creatphone,
      //获取手机颜色
  "getColor" : function(){
  return this._color;
  },
      //设置手机颜色
  "setColor" : function(color){
  this._color = color;
  },
      //获取手机大小
  "getSize" : function(){
  return "width:"+this._size.width + " height:" + this._size.height;
  },
      //设置手机大小
  "setSize" : function(size){
  this._size.width = size.width;
  this._size.height = size.height;
  },
      //获取手机价格
  "getPrice" : function(){
  return this._price;
  },
      //设置手机价格
  "setPrice" : function(price){
  this._price = price
  }
 }
})()

위에 캡슐화된 휴대폰 클래스를 사용하여 테스트
var MobilePhone = (function(){
 //私有属性
 var count = 0;//代表手机的数量
 var index = 0;//代表手机的索引
     //构造函数
     var creatphone = function(color,size,price){
         count++;
         this._color = color; //手机的颜色
         this._size = size; //手机的大小
         this._price = price; //手机的价格
         this.index = count; //手机索引,是第几台创建的手机手象
       }
     //公有方法,存放在原型对象中
 creatphone.prototype = {
  "constructor":creatphone,
  "getColor" : function(){
  return this._color;
  },
  "setColor" : function(color){
  this._color = color;
  },
  "getSize" : function(){
  return "width:"+this._size.width + " height:" + this._size.height;
  },
  "setSize" : function(size){
  this._size.width = size.width;
  this._size.height = size.height;
  },
  "getPrice" : function(){
  return this._price;
  },
  "setPrice" : function(price){
  this._price = price
  }
 }
 //特权方法
 creatphone.get_count_index = function(){
  return count
 }
 return creatphone;
})()

Javascript의 더 많은 측면 객체 캡슐화와 관련된 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

var anycall = new MobilePhone(); //实例一个三星手机对象
var HTC = new MobilePhone(); //实例一个HTC手机对象
var Iphone4s = new MobilePhone(); //实例一个苹果4S手机对象
console.log("三星是第:"+anycall.index+"台"); //FF的控制台输出三星手机对象是第几台创建的,即索引;
console.log("HTC是第:"+HTC.index+"台"); //FF的控制台输出HTC手机对象是第几台创建的,即索引;
console.log("Iphone4s是第:"+Iphone4s.index+"台");  //FF的控制台输出个苹果4S手机对象是第几台创建的,即索引;
console.log("总共造出了"+MobilePhone.get_count_index()+"手机"); //FF的控制台输出总共创建了几台手机;
console.log(anycall.constructor === MobilePhone); //实例出来的对象,的原形象中的constructor,是否还指向MobilePhone


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.