js 构造函数(construction)与原型(prototype)

1.面向对象:js原型

java有class和instance,js仅仅有构造函数(function Cat(name,age){this.name=name;this.age=age}),为了实现数据共享和抽象出通用的属性,加了一个原型prototype

     eg:

function Cat(name,age){

this.name = name;//这里的this相当于java里面的instance

this.age = age;

this.work = function(){

alert("I am working");

}

}


var cat1 = new Cat("cat1",13);

var cat2 = new Cat("cat2",15);

cat1和cat2的都有work属性,可是一样的属性,明显是多余的,造成浪费。能够抽象出原型出来

function Dog(name,age){

this.name = name;

this.age = age;

}


Dog.prototype = {work:function(){alert("I am working!")}}或者

Dog.prototype.work = function(){

alert("I am working");

}

2.封装:

原始模式:var cat = {};cat.name = "cat1";cat.id = "id1";

原始模式改进:var cat = function cat(name,id){return {name:name,id:id}},相当于调用函数

构造函数模式:function(name,id){this.name = name;this.id=id}

js中构造函数在初始化的时候加new和不加new的差别

function Dog(name,age){

this.name = name;

this.age = age;

}


Dog.prototype = {work:function(){alert("I am working!")}}

var dog1 = Dog("dog1",12);//这仅仅是相当于调用普通函数。原型work不会生成,调用work属性会报错

var dog2 = new Dog("dog2",13);//这里是调用构造函数,初始化原型work

var dog3 = new Dog("dog3",14);

dog2.constructor == Dog;   dog3.constructor == Dog


为了解决从原型对象生成实例的问题,Javascript提供了一个构造函数(Constructor)模式。

所谓"构造函数",事实上就是一个普通函数,可是内部使用了this变量。对构造函数使用new运算符,就能生成实例。而且this变量会绑定在实例对象上。


3.继承

(1)对象冒充

function ClassA(sColor) {
    this.color = sColor;
    this.sayColor = function () {
        alert(this.color);
    };
}

function ClassB(sColor) {
}
function ClassB(sColor) {
    this.newMethod = ClassA;
    this.newMethod(sColor);
    delete this.newMethod;
}

在这段代码中,为 ClassA 赋予了方法 newMethod(请记住。函数名仅仅是指向它的指针)。然后调用该方法。传递给它的是 ClassB 构造函数的參数 sColor。最后一行代码删除了对 ClassA 的引用,这样以后就不能再调用它。

全部新属性和新方法都必须在删除了新方法的代码行后定义。否则。可能会覆盖超类的相关属性和方法:

function ClassB(sColor, sName) {
    this.newMethod = ClassA;
    this.newMethod(sColor);
    delete this.newMethod;

    this.name = sName;
    this.sayName = function () {
        alert(this.name);
    };
}
var objA = new ClassA("blue");
var objB = new ClassB("red", "John");
objA.sayColor();	//输出 "blue"
objB.sayColor();	//输出 "red"
objB.sayName();		//输出 "John"



原文地址:https://www.cnblogs.com/mfmdaoyou/p/7324835.html