Home  >  Article  >  Web Front-end  >  Simple implementation method of JavaScript object encapsulation (3 methods)

Simple implementation method of JavaScript object encapsulation (3 methods)

高洛峰
高洛峰Original
2017-01-04 09:39:021198browse

The example in this article describes the simple implementation method of JavaScript object encapsulation. Share it with everyone for your reference, the details are as follows:

Javascript is becoming more and more powerful in HTML, rich client, WebGL in HTML5, etc. But when we write Javascript, we tend to be very casual, and using object encapsulation is excellent. Here are three ways to create objects in Javascript.

1. Use the keyword new to create an object

function Person(name, age) {
 this.name = name;
 this.age = age;
}
var p = new Person();  // 也可填充初始化属性,如new Person("lingceng", 22)

2. Use Object to directly create an object

It can be seen that this method is very convenient to expand.

var obj = new Object(); // 这里也可写成 var = {};
obj.name = "lingceng";
obj.age = 22;

3. Use JSON to create (object literals are more accurate, but JSON is easier to understand)

Starting from Javascript 1.2, there is a faster way to create objects.

var p = {
 name: "lingceng", // "name":"lingceng这样加引号解析方式相同
 gender: "male"
};

Practice method

The method of creating objects by combining constructors and prototype patterns is very suitable for practice.

function Person(name,age)
{
  // 实例属性
  // 实例时多份拷贝
  this.name=name;
  this.age=age;
}
Person.prototype={
  // 因为原型被替换,所以需要恢复construtor的默认指向
  constructor: Person,
  showName:function(){
    alert("ShowName in prototype:"+this.name);
  },
  showAge:function(){
    alert(this.age);
  }
}
var p = new Person("lingceng", 22);
p.showAge(); // 22

I hope this article will be helpful to everyone in JavaScript programming.

For more simple implementation methods of JavaScript object encapsulation (3 methods), please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn