Home >Web Front-end >JS Tutorial >Summary of ways to create objects in JavaScript (4 ways)_javascript skills

Summary of ways to create objects in JavaScript (4 ways)_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:25:051259browse

The examples in this article summarize the way JavaScript creates objects. Share it with everyone for your reference, the details are as follows:

Subconsciously, JavaScript cannot be regarded as an object-oriented language. If it is, it can only be said to be a language that tends to be object-oriented. At least it does not fit well with the three most basic characteristics of object-oriented (inheritance, encapsulation, and multiplexing). state), of course many people think that JavaScript is an object-oriented language, and they seem to be right, because object-oriented can also be implemented in JavaScript. For example, inheritance and encapsulation can also be implemented in JavaScript, but is it easy to implement? ?So I feel very confused. I saw a netizen on the Internet commenting very well, "Object-oriented is just an idea, and the language can only say whether it supports object-oriented features well." If you have a certain understanding of object-oriented, you can also write object-oriented programs in C program, the same is true for javascript. So I can’t say that JavaScript is an object-oriented language. Haha, I think I’m a novice and I don’t dare to make such claims. Let’s take a look at the code:

1. Use json to create objects

var company = {};
company.name= '华为';
company.address = '北京';
company.produce = function(message)
{
 alert(message);
}

2. Use the Object type in JavaScript

company= new Object();
company.name= '淘宝';
company.address = '杭州';
company.produce= function(message)
{
 alert(message);
}

3. Generate objects by creating functions

company = function()
{
  this.name = '新浪';
  this.address = '北京';
  this.produce = function(message)
  {
  alert(message);
  }
}

4. Use the browser window object

window.name = '腾讯';
window.address = '北京';
window.produce = function(message)
{
  alert(message);
}

Extension:

1. Object copy

emptyObject = new Object();
company.apply = function(o, c,)
{
  if(o && c && typeof c == 'object')
  {
  for(var p in c)
  {
  o[p] = c[p];
  }
  }
  return o;
};
emptyObject = Ext.apply(emptyObject,company);

2. Object copy (function method)

var copyOO = new Function();
copyOO.prototype = company;
var newcopyOO = new copyOO();

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

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