javascript 继承

复制代码
    //对象冒充实现继承
    function Person() {
        this.speak = function () {
            alert("我是人类");
        };
    }

    function Chinese() {
        Person.call(this);
    }
    var p = new Chinese();
    p.speak();

//对象冒充与原型继承
    function Person(sColor) {
        this.color = sColor;
    }

    Person.prototype.sayColor = function () {
        alert(this.color);
    };

    function Chinese(sColor, sName) {

        Person.call(this, sColor);//对象冒充继承属性

        this.name = sName;
    }

    Chinese.prototype = new Person();//原型继承方法

    Chinese.prototype.sayName = function () {
        alert(this.name);
    };

    var p = new Chinese("red", "高聪");
    p.sayColor();
    p.sayName();
复制代码

 

复制代码
//Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); //call super constructor.
}

Rectangle.prototype = Object.create(Shape.prototype);

var rect = new Rectangle();

rect instanceof Rectangle //true.
rect instanceof Shape //true.

rect.move(1, 1); //Outputs, "Shape moved."
复制代码
该方法属于ES5规范,如果浏览器环境不支持也可以自行实现,如下:

Object.create = Object.create || function (obj) {
            var F = function () {};
            F.prototype = obj;
            return new F();
        }

 

posted @   小小高  阅读(174)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示