This article mainly introduces how JavaScript creates objects, summarizes and analyzes four ways to create objects in the form of examples, and also analyzes JavaScript objects copying techniques. Friends in need can refer to
The examples in this article summarize the way to create objects in JavaScript. 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 It does not fit well with the three most basic characteristics of object-oriented (inheritance, encapsulation, polymorphism). Of course, many people think that JavaScript is an object-oriented language, which seems to be correct, 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 a 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. Utilize 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 mode)
var copyOO = new Function(); copyOO.prototype = company; var newcopyOO = new copyOO();
The above is the detailed content of 4 ways to create objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website!