Home  >  Article  >  Web Front-end  >  JavaScript cannot create objects

JavaScript cannot create objects

WBOY
WBOYOriginal
2022-04-11 10:07:262392browse

JavaScript can create objects. Creation method: 1. Use Object to create an object directly, the syntax is "new Object()"; 2. Use the new keyword to create an object, the syntax is "new object name()"; 3. Use JSON to create an object, the syntax is "object={property" Name: attribute value,...}".

JavaScript cannot create objects

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

Can JavaScript not create objects?

A JavaScript object is a variable that can hold many different values. It acts as a container for a set of related values. For example, users of a website and bills in a bank account can all be JavaScript objects.

In JavaScript, objects contain two types of values: properties and methods.

When you create a JavaScript object, you need to define its name, properties, and methods.

Method to create a JavaScript object:

1. Use Object to create the object directly

var myObj=new Object();//使用Object类创建一个空的对象
 
myObj.name="wangshihcheng";
 
myObj.age=20;
 
myObj.infor=function(){
 
document.write("名字:"+this.name);//this.的指向问题
 
document.write("年龄:"+this.age);
 
}
 
myObj.infor();//调用创建的对象里面的方法;

2. Use the new keyword to call the constructor to create an object.

The code is as follows:

<script>
    var obj = new Object();
    obj.name = "Kitty";//为对象增加属性
    obj.age = 21;
    obj.showName = function () {//为对象添加方法
        console.log(this.name);
    };
    obj.showAge = function(){
        console.log(this.age);
    };
    obj.showName();
    obj.showAge();
</script>

This method generates an object through the new keyword, and then adds attributes according to the characteristics of JavaScript as a dynamic language. and methods to construct an object. The this represents the object on which the method is called.

The problem with this method is: if we need to create objects multiple times, then we need to repeat the code multiple times, which is not conducive to code reuse.

3. Use prototype mode to create objects

In JavaScript, each function has a prototype attribute, which is a pointer pointing to an object, called

Prototype object, the prototype object contains properties and methods that can be shared by all instance objects of a specific type;

In addition, this object has a built-in attribute constructor, which points to the constructor method of creating the object;

When we use the prototype pattern, all instances can share the properties and methods of the prototype object,

Therefore we do not need to define the instance information of the object in the constructor;

function Student(){
        
 
}
Student.prototype.name="wang";
Student.prototype.sex="man";
Student.prototype.class="5";
Student.prototype.sayName=function(){
    console.log(this.name);
}
 
var s1=new Student();
s1.sayName();//wang
 
var s2=new Student();
s2.sayName();//wang
 
s2.name="shicheng";
s2.sayName();//shicheng

When we read the properties of an object, a search will be performed. The search first starts from the object instance itself.

If the property is found in the instance, the search ends and the value of the property is returned. ;

If it is not found on the instance, continue to extend to the prototype object of the object and search the prototype object of the object. If

finds this attribute on the prototype, return the corresponding attribute on the prototype If the value is not found, undefine is returned;

Therefore, it can be seen that the instance object properties will overwrite the properties on the prototype object;

4. Use JSON to create objects

//object={Attribute name 1: attribute value 1, attribute name 2: attribute value 2,...}

//Note that the attribute name in JOSN format must be Add double quotes;

var p={
 
"name":"wangsch",
 
"gender":"man",
 
"age":40,
 
"son":[
 
    {
 
        "name":"son1",
 
        "age":2
 
    },
 
    {
 
    "name":"son2",
 
    "age":5
 
    }
 
],
 
"infor":function(){
 
document.write("父亲的姓名:"+this.name+",父亲的年龄:"+this.age+"<br>");
 
for( var child in this.son ){
 
document.write("儿子的姓名:"+this.son[child].name+",儿子的年龄:"+this.son[child].age+"<br>");
 
                }
 
        }
 
}
 
p.infor();//调用对象p中的infor方法

5. Create objects using a combination of constructors and prototype patterns

The constructor is used to define the attributes of the instance, and the prototype pattern is used to define methods and shared attributes;

function Student(name,sex,grade){
    this.name=name;
    this.sex=sex;
    this.grade=grade;
}
 
Student.prototype.sayName=function(){
    console.log(this.name);
}
 
Student.prototype.school="nongda";

This mixed mode can support passing parameters into the constructor and also greatly saves memory.

6. Create objects using dynamic prototype methods.

The code is as follows:

<script>
    function Person(name,age){
        this.name = name;
        this.age = age;
        this.array = new Array("Kitty","luo");
        //如果Person对象中_initialized 为undefined,表明还没有为Person的原型添加方法
        if(typeof Person._initialized  == "undefined"){
            Person.prototype.showName = function () {
                console.log(this.name);
            };
            Person.prototype.showArray = function () {
                console.log(this.array);
            };
            Person._initialized = true;
        }
    }
  
    var obj1 = new Person("Kitty",21);
    var obj2 = new Person("luo",22);
    obj1.array.push("Wendy");//向obj1的array属性添加一个元素
  
    obj1.showArray();//Kitty,luo,Wendy
    obj1.showName();//Kitty
    obj2.showArray();//Kitty,luo
    obj2.showName();//luo
</script>

This method is similar to the constructor/prototype method. Just add the method to the constructor, and add an attribute to the constructor Person to ensure that the if statement can only be executed successfully once. In practical applications, the most widely used constructor/prototype method is used. Dynamic prototype methods are also popular and are functionally equivalent to constructor/prototype methods. Don't use constructors and prototype methods alone.

【Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of JavaScript cannot create objects. For more information, please follow other related articles on 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