JavaScript学习-面向对象与原型3

版权声明:本文为博主原创文章,欢迎转载。 https://blog.csdn.net/fww330666557/article/details/78763682

字面量方式创建原型

为了让属性和方法更好地体现封装的效果,并且减少不必要的输入,原型的创建可以使用字面量的方式。

function Box(){}
Box.prototype = {
    name:'Lee',// 原型属性
    age:100,// 原型属性
    run :function(){// 原型方法
        return this.name + this.age +'运行中...';
    }
}
var box1 = new Box();

document.write(box1.name)
document.write("<br/>")
document.write(box1.age)
document.write("<br/>")
document.write(box1.run())

运行结果:

Lee
100
Lee100运行中...

其结果与使用构造函数方式创建的原型是一样的。

构造函数方式与字面量方式的区别

字面量创建的方式使用constructor属性不会指向实例,而会指向Object;构造函数创建方式正好相反。
对于构造函数方式:

var box1 = new Box();
document.write(box1.constructor)

输出:

function Box(){}

而对于字面量方式,则输出:

function Object() { [native code] }

为什么会有这种区别呢?因为Box.prototype = { }这种写法其实就是创建了一个新的对象。而每创建一个函数,就会同时创建它的prototype,这个对象会自动获取constructor属性。所以新对象的constructor重写了Box原来的constructor,因此会指向新对象,那个新对象没有制定构造函数,那么默认为Object。

强制指向实例

function Box(){}
Box.prototype = {
    constructor :Box,// 强制指向Box
    name:'Lee',
    age:100,
    run :function(){
        return this.name + this.age +'运行中...';
    }
}
// 测试代码
var box1 = new Box();
document.write(box1.constructor)

输出结果:

function Box(){}

重写原型对象

// 原型
function Box(){}
Box.prototype = {
    constructor :Box,
    name:'Lee',
    age:100,
    run :function(){
        return this.name + this.age +'运行中...';
    }
}
// 重写原型对象
Box.prototype = {
    age:200 
}
// 测试代码
var box1 = new Box();
document.write(box1.name)

输出结果:

undefined

重写之后,不会保留之前原型的任何信息了。把原来的原型对象和构造函数对象实例之间的关系切断了。

关于原型的进一步说明

原型对象不仅可以在自定义对象的情况下使用,ECMAScript内置的引用类型都可以使用这种方式,并且内置引用类型本身也使用了原型。

查看sort是否是Array原型对象里的方法

document.write(Array.prototype.sort)

输出:

function sort() { [native code] }

内置引用类型的功能扩展(不推荐)

String.prototype.addString = function(){
    return this + '被添加了!';
}
var box = 'Lee';
document.write(box.addString());

输出:

Lee被添加了!

猜你喜欢

转载自blog.csdn.net/fww330666557/article/details/78763682