JavaScript Basics (6) Object-Oriented

object oriented

Object creation method:

1. Call system functions to create objects

(The easiest way to create an object is to create an instance of Object and then add properties and methods to it.)

var obj = new Object();
obj.name = "Daotin";
obj.age = 18;
obj.eat = function () {
  console.log("我很能吃");
);

Disadvantage: Creating many objects with the same interface creates a lot of duplication of code.

2. Create an object with a custom constructor

Factory pattern to create objects : Considering that classes cannot be created in ECMAScript, developers invent a function that encapsulates the details of creating objects with a specific interface (encapsulates the process of creating a function in a function). Disadvantages: The created object properties are all the same.

function creatObject() {
    var obj = new Object();
    obj.name = "Daotin";
    obj.age = 18;
    obj.eat = function () {
        console.log("我很能吃");
    };
    return obj;
}

var person = creatObject();
person.eat();

Advanced version of the factory pattern to create objects: properties can be modified

function creatObject(name, age) {
    var obj = new Object();
    obj.name = name;
    obj.age = age;
    obj.eat = function () {
        console.log("我很能吃");
    };
    return obj;
}java

var person = creatObject("Daotin", 18);
person.eat();

Custom constructors: (Difference between functions and constructors: no difference, but usually constructors are capitalized )

Features:

  • Objects are not created explicitly;
  • Directly assign properties and methods to this object;

  • There is no return statement.

function CreatObject() { // 首字母大写
    this.name = "Daotin";
    this.age = 18;
    this.eat = function () {
        console.log("我很能吃");
    };
}

var person = new CreatObject();
person.eat();

Advanced (pass parameters):

function CreatObject(name, age) {
    this.name = name;
    this.age = age;
    this.eat = function () {
        console.log("我很能吃");
    };
}

var person = new CreatObject();
person.eat();

Constructor problem

While the Constructor pattern is useful, it is not without its drawbacks. The main problem with using constructors is that each method is recreated on each instance. In the previous example, both person1 and person2 have a method called sayName(), but those two methods are not instances of the same Function. Don't forget - functions in ECMAScript are objects, so every time a function is defined, an object is instantiated. From a logical point of view, the constructor at this time can also be defined in this way.

function Person(name, age, job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = new Function("alert(this.name)"); // 与声明函数在逻辑上是等价的
}

Looking at the constructor from this perspective, it's easier to see the nature of each Person instance containing a different Function instance (to display the name property). To be clear, creating functions this way results in a different scope chain and identifier resolution, but the mechanism for creating new instances of Function remains the same. Therefore, functions of the same name on different instances are not equal, as demonstrated by the following code:alert(person1.sayName == person2.sayName); //false

However, it's really not necessary to create two Function instances that do the same thing; with the this object there, there's no need to bind the function to a specific object before executing the code. Therefore, the problem can be solved by moving the function definition outside the constructor as follows.

function Person(name, age, job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = sayName;
}

function sayName(){
    alert(this.name);
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");

In this example, we moved the definition of the sayName() function outside the constructor. Inside the constructor, we set the sayName property equal to the global sayName function. This way, since sayName contains a pointer to a function, the person1 and person2 objects share the same sayName() function defined in the global scope.

3. Use Object Literal Notation

Object literals are a shorthand form of object definitions designed to simplify the process of creating objects with a large number of properties.

If you leave its curly braces blank, you can define an object containing only default properties and methods var person = {}; // same as new Object().

Disadvantage: A one-time object, cannot modify the value of the property.

var obj = {
    name:"Daotin",  // 注意是属性赋值是冒号
    age: 18,
    eat: function () {
        console.log("我很能吃");
    }   // 最后一个后面没有逗号
};

obj.eat();

Access object properties

Dot notation and square bracket notation

alert(person["name"]); //"Nicholas"
alert(person.name); //"Nicholas"

Functionally, there is no difference between the two methods of accessing object properties. But the main advantage of the square bracket syntax is that properties can be accessed through variables (property binding), for example:

var propertyName = "name";
alert(person[propertyName]); //"Nicholas"

You can also use square bracket notation if the property name contains characters that cause a syntax error, or if the property name uses a keyword or reserved word.

For example: person["first name"] = "Nicholas";
"first name" cannot be accessed using dot notation because it contains a space. However, property names can contain non-alphanumeric characters, in which case they can be accessed using square bracket notation. In general, we recommend using dot notation unless variables must be used to access properties.

PS: If you access the value of a property that does not have it, then the value is undefined instead of an error?

Because js is a dynamic type of element, no matter whether it uses dot notation or square bracket notation, if there is no such attribute, it is equivalent to creating this attribute. However, there is no assignment at this time, so it is undefined.

access object method

对象名.函数名();

JSON

What is JSON?

JavaScript Object Notation (JavaScript Object Representation: It's Object Literal)

Data in JSON format: generally in pairs, key-value pairs.

Difference between JSON and object literals?
The difference between json and objects (object literals) is only that keys in json-formatted data must be enclosed in double quotes;

var json = {
    "name" : "zs",
    "age" : 18,
    "sex" : true,
    "sayHi" : function() {
        console.log(this.name);
    }
};    

literal traversal

The object itself has no length, so it cannot be traversed with a for loop. To use for...in...

var json = {“aaa”: 1, “bbb”: 2, “ccc”: 3, “ddd”: 4}

for(var key in json){
    //key代表aaa,bbb.....等
    //json[key]代表1,2,3....等(k 不要加引号)
}

pass-by-value and pass-by-reference

The best way to analyze value transfer and address transfer is to draw and analyze, which is the easiest.

built-in objects

Math, Date, String, Array

MDN: Online Documentation

rookie tutorial

Basic packaging type

It is a basic type itself, but in the process of execution, if a variable of this type calls a property or method, then this type is not a basic type, but a basic wrapper type. This variable is not a normal variable anymore, but a variable of the basic wrapper type.

var str = "hello";
str = str.replace("he", "wo");
console.log(str); // wollo

Points to note:

If an object &&true, then the result is true

If a true && object, then the result is the object.

var flag = new Boolean(false);
var result = flag && true;
var result1 = true && flag;

console.log(result); // true
console.log(result1); // Boolean
var num = 10; // 基本类型
var num2 = Number("10"); // 不是基本包装类型,而是转换,这里换成 Boolean 也成立
var num3 = new Number("10"); // 这才是基本包装类型

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325206962&siteId=291194637