JavaScript学习笔记

时间:2021-09-16
本文章向大家介绍JavaScript学习笔记,主要包括JavaScript学习笔记使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

创建对象

工厂模式

function createPerson(name, age, job){
    var o = new Object();
    o.name = name;
    o.age = age;
    o.job = job;
    o.sayName = function(){
        alert(this.name);
    };
    return o;
}

构造函数模式

  • 没有显示创建对象
  • 直接将属性和方法赋给了this对象
  • 没有return语句
function Person(name, age, job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = function(){
    	alert(this.name);
    };
}

Prototype原型

组合使用构造函数模式和原型模式


function Person(name, age, job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.friends = ["Shelby","court"];
}

Person.prototype = {
    constructor : Person;
    sayName : function (){
        alert(this.name)
    }
}

var person1 = new Person("Nicholas",29,"Software Engineer");
var person2 = new Person("Greg",27,"Doctor");

person1.friends.push("Van");
alert(person1.friends);//"Shelby","court","Van"
alert(person2.friends);//"Shelby","court",
alert(person1.friends === person2.friends);//false  ===全等 判断引用 ==等于 判断值
alert(person1.sayName === person2.sayName);//ture

动态原型模式

原文地址:https://www.cnblogs.com/josuke/p/15294283.html