René's URL Explorer Experiment


Title: 谈js继承 · Issue #5 · wython/wython.github.io · GitHub

Open Graph Title: 谈js继承 · Issue #5 · wython/wython.github.io

X Title: 谈js继承 · Issue #5 · wython/wython.github.io

Description: 谈js继承 js没有提供面向对象编程的语法特性,也没有类的概念。在es6中可以使用class去定义类和继承,但是实际上却没有面向对象多态的这些特性。其底层依然是基于js的原型链去实现的。 js可以基于Object创建对象(如下),但是Object本质更像是键值对的哈希对象,所以基于Object字面量和简单的方式创建对象往往无法满足我们要求。 let o = new Object(); let p = { name: 'person' }; 通过函数方式创建对象 通过函数...

Open Graph Description: 谈js继承 js没有提供面向对象编程的语法特性,也没有类的概念。在es6中可以使用class去定义类和继承,但是实际上却没有面向对象多态的这些特性。其底层依然是基于js的原型链去实现的。 js可以基于Object创建对象(如下),但是Object本质更像是键值对的哈希对象,所以基于Object字面量和简单的方式创建对象往往无法满足我们要求。 let o = new Object(); let...

X Description: 谈js继承 js没有提供面向对象编程的语法特性,也没有类的概念。在es6中可以使用class去定义类和继承,但是实际上却没有面向对象多态的这些特性。其底层依然是基于js的原型链去实现的。 js可以基于Object创建对象(如下),但是Object本质更像是键值对的哈希对象,所以基于Object字面量和简单的方式创建对象往往无法满足我们要求。 let o = new Object(); let...

Opengraph URL: https://github.com/wython/wython.github.io/issues/5

X: @github

direct link

Domain: patch-diff.githubusercontent.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"谈js继承","articleBody":"##  谈js继承\r\n\r\njs没有提供面向对象编程的语法特性,也没有类的概念。在es6中可以使用class去定义类和继承,但是实际上却没有面向对象多态的这些特性。其底层依然是基于js的原型链去实现的。\r\n\r\njs可以基于Object创建对象(如下),但是Object本质更像是键值对的哈希对象,所以基于Object字面量和简单的方式创建对象往往无法满足我们要求。\r\n\r\n```\r\nlet o = new Object();\r\nlet p = { name: 'person' };\r\n```\r\n\r\n### 通过函数方式创建对象\r\n通过函数方式也可以很好的创建对象,而且从代码复用性和封装性都比以上方式好。\r\n\r\n```javascript\r\nfunction Animal(type, name) {\r\n  this.type = type || 'animal';\r\n  this.name = name || 'anonymity'\r\n  this.sayName = function (){\r\n    console.log(`${this.type}: ${this.name}`);\r\n  }\r\n}\r\n\r\n// Animal('person'); 与普通函数无异\r\n// new Animal('person'); 返回对象\r\n\r\n```\r\n通过new操作符,经历里一下步骤\r\n\r\n1. 函数创建一个新对象\r\n2. 将函数内部上下文赋予新对象\r\n3. 执行函数代码\r\n4. 返回新建对象\r\n\r\n所以说,通过new方式,我们获得的是这个新创建的对象。因此,可以很方便的创造各种实例,如下:\r\n\r\n```\r\nconst person = new Animal('person');\r\nconst dog = new Animal('dog');\r\n\r\nperson.sayName(); // 输出 person: anonymity\r\ndog.sayName(); // 输出 dog: anonymity\r\n```\r\n但是其实很快就有新的问题,\r\n\r\n```\r\nperson.sayName === dog.sayName\r\n// 输出false\r\n```\r\n\r\n我们发现对于某些可以复用的代码,实际上重复执行了,说白了就是,sayName函数实际上只需要存在一份即可,但是实际运行过程中,不同实例都声明了不同的函数。这实际不是一个优雅的方式。所以引出下一个概念,原型链。\r\n\r\n### 原型对象\r\n希望读者先区分构造函数和实例两个不同的名词,首先,如果细心就会发现,对于元生对象如Object, Array之类的(本质依然是function)构造函数,都具有prototype属性。像我们自己定义的Animal函数,也具有一个prototype属性。\r\n这个prototype属性指向的是原型对象的引用。每一个函数在创建过程中,会生成一个原型对象,同时,构造函数本身的prototype属性指向这个原型对象。细心点也会发现,通过new创建的实例person,dog具有__proto__属性。这是一个已废弃的属性,但是它的存在说明了实例上面也有指向原型对象的引用。不推荐用__proto__访问原型对象,那有什么办法可以访问实例的原型对象。可以通过Object.getPrototypeOf(person)方式获得实例的原型对象,实例的原型对象和构造函数的原型对象是不是一致的,答案是肯定的。\r\n```\r\nObject.getPrototypeOf(person) === Animal.prototype\r\n// true\r\n```\r\n同时,原型对象上有constructor属性是指向构造函数本身的。\r\n```\r\nAnimal.prototype.constructor === Animal\r\n// true\r\n```\r\n所以可以总结为,当函数被创建时,会有一个prototype属性指向一个生成的原型对象, 并且原型对象具有指回构造函数的引用contructor属性。当通过构造函数创建实例时,实例也拥有指向原型对象的属性(即实例可以追溯原型对象)。\r\n\r\n### 原型对象作用之共用公共属性\r\n在别的语言里可以通过static声明公共的属性,js的原型对象有这样用处。因为实例访问属性的过程中,会遍历自身属性,如果没有会追溯原型链的属性。也就是说,实例可以访问到原型对象上的属性。同时所有实例共享同一个原型对象。\r\n```\r\nObject.getPrototypeOf(person) === Object.getPrototypeOf(dog);\r\n\r\n// true\r\n```\r\n这也就达到一份代码可以多实例复用的要求。所以构造函数写成:\r\n```javascript\r\nfunction Animal(type, name) {\r\n  this.type = type || 'animal';\r\n  this.name = name || 'anonymity'\r\n}\r\nAnimal.prototype.sayName = function (){\r\n  console.log(`${this.type}: ${this.name}`);\r\n}\r\nAnimal.prototype.publicProper = 'p';\r\n```\r\n\r\n如果希望构造函数看上去封装性更好,可以优化\r\n\r\n```javascript\r\nfunction Animal(type, name) {\r\n  this.type = type || 'animal';\r\n  this.name = name || 'anonymity'\r\n\r\n  if (typeof this.sayName !== 'function') {\r\n    Animal.prototype.sayName = function (){\r\n      console.log(`${this.type}: ${this.name}`);\r\n    }\r\n  }\r\n}\r\n```\r\n\r\n### 原型对象作用二之继承\r\n讲了这么久,才到真正要讨论的内容,因为js真正属于面向对象特性的还是继承。有以上基础其实可以很简单的实现继承。最简单,最直接一般都是这样做\r\n\r\n```javascript\r\nfunction Animal(type, name) {\r\n  this.type = type || 'animal';\r\n  this.name = name || 'anonymity'\r\n\r\n  if (typeof this.sayName !== 'function') {\r\n    Animal.prototype.sayName = function () {\r\n      console.log(`${this.type}: ${this.name}`);\r\n    }\r\n  }\r\n}\r\n\r\nfunction Person(type, name) {\r\n  this.name = name | 'anonymity';\r\n}\r\n\r\nPerson.prototype = new Animal('person');\r\n```\r\n这样最简单的继承就实现了,但是这种继承方式存在缺点。\r\n\r\n1. 因为子类Person的原型是Animal的实例,所Person创建的实例也包含了Animal实例的属性,Person不同实例共用Animal的实例属性。是不是有办法,当Animal的实例属性继承下来是Person的实例属性。\r\n\r\n2. Animal构造函数是有参数的,这种方式因为是公用的,所以我们继承new Animal时候没有传参数name,因为我们默认Animal的name属性是需要覆盖的。明显这样写法灵活性不够。或者说,如果希望type, name属性依然是实例属性,实际上继承Animal构造函数的代码没有复用到。\r\n\r\n3. 子类新原型对象并没有constructor属性指回构造函数,与原生方式不同。\r\n\r\n### 借用父类构造函数\r\n\r\n可以通过在子类中调用父类构造函数,并且改变作用域,将实例属性赋值到子类的实例属性上\r\n\r\n```javascript\r\nfunction Animal(type, name) {\r\n  this.type = type || 'animal';\r\n  this.name = name || 'anonymity'\r\n\r\n  if (typeof this.sayName !== 'function') {\r\n    Animal.prototype.sayName = function () {\r\n      console.log(`${this.type}: ${this.name}`);\r\n    }\r\n  }\r\n}\r\n\r\nfunction Person(name) {\r\n  this.job = null;\r\n  Animal.call(this, 'person', name);\r\n}\r\n\r\nPerson.prototype = new Animal();\r\nPerson.prototype.constructor = Person;\r\n\r\nconst p = new Person('peter');\r\n\r\np.sayName();\r\n\r\n// Person peter\r\n```\r\n\r\n这样实现,大体上是已经很完美了, 但是依然有不足,一个是构造函数执行两次,所以原型属性上和实例属性上重复了。为了解决这个问题,我们最直观的想法时就是创建一个空对象并且,然后将原型上的内容复制到空对象上。实际上,我们一个可以创建一个空白构造函数,并且使其原型为父类原型,再将空白对象实例作为之类原型即可。用代码直观点:\r\n\r\n```javascript\r\nfunction objectCreate(proto) {\r\n  function F(){};\r\n  F.prototype = proto;\r\n  return new F();\r\n}\r\n// 继承代码改写为\r\nfunction Animal(type, name) {\r\n  this.type = type || 'animal';\r\n  this.name = name || 'anonymity'\r\n\r\n  if (typeof this.sayName !== 'function') {\r\n    Animal.prototype.sayName = function () {\r\n      console.log(`${this.type}: ${this.name}`);\r\n    }\r\n  }\r\n}\r\n\r\nfunction Person(name) {\r\n  this.job = null;\r\n  Animal.call(this, 'person', name);\r\n}\r\n\r\nPerson.prototype = objectCreate(Animal.prototype);\r\nPerson.prototype.constructor = Person;\r\n\r\nconst p = new Person('peter');\r\np.sayName();\r\n// Person peter\r\n```\r\n当然es5中已经提供了object.create()方法。\r\n\r\n到此,继承的所有讨论就结束了,在es6,和ts已经这么普及的今天,讨论这一个老生常谈的问题,有必要吗?我觉得还是有必要的,第一,我觉得对于这样问题,并不是所有人都真正的理解其中的含义。第二,我觉得只要浏览器没有完全支持新语法,那么意味着我们最终跑得前端代码依然是很原始的代码,在这个角度去理解这些代码是有益的。最后,我个人也觉得,对于继承这个话题,在红皮书上有各种各样的定义,很多人太拘泥于它的命名,反而忽视了一些内容背后解决的问题,这些命名其实是从英文在通过翻译者翻译,并不是真正需要去理解的东西。\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","author":{"url":"https://github.com/wython","@type":"Person","name":"wython"},"datePublished":"2019-07-19T08:44:13.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":0},"url":"https://github.com/5/wython.github.io/issues/5"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:4ba580c9-be2c-fb1a-24cf-6520cb21586a
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idB050:2586AA:1C9049A:24A0986:69757F38
html-safe-noncea82ed4a053c508b3a12ac8021f65fd379cec444cb4d69e62d2f7f1d85108ae47
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCMDUwOjI1ODZBQToxQzkwNDlBOjI0QTA5ODY6Njk3NTdGMzgiLCJ2aXNpdG9yX2lkIjoiNjMxODIxMDE3MjQ2MjY3NDQiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmac9e3a97af3880f691a151c4529e8524848453679cfec3e075f001911a97cdb6ba
hovercard-subject-tagissue:470209644
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/wython/wython.github.io/5/issue_layout
twitter:imagehttps://opengraph.githubassets.com/6369fa9246c559e5fceecb1ba5c5f299d31715e2aa0ccd2d5413bb757b630205/wython/wython.github.io/issues/5
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/6369fa9246c559e5fceecb1ba5c5f299d31715e2aa0ccd2d5413bb757b630205/wython/wython.github.io/issues/5
og:image:alt谈js继承 js没有提供面向对象编程的语法特性,也没有类的概念。在es6中可以使用class去定义类和继承,但是实际上却没有面向对象多态的这些特性。其底层依然是基于js的原型链去实现的。 js可以基于Object创建对象(如下),但是Object本质更像是键值对的哈希对象,所以基于Object字面量和简单的方式创建对象往往无法满足我们要求。 let o = new Object(); let...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamewython
hostnamegithub.com
expected-hostnamegithub.com
None4a4bf5f4e28041a9d2e5c107d7d20b78b4294ba261cab243b28167c16a623a1f
turbo-cache-controlno-preview
go-importgithub.com/wython/wython.github.io git https://github.com/wython/wython.github.io.git
octolytics-dimension-user_id15258919
octolytics-dimension-user_loginwython
octolytics-dimension-repository_id142893945
octolytics-dimension-repository_nwowython/wython.github.io
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id142893945
octolytics-dimension-repository_network_root_nwowython/wython.github.io
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release488b30e96dfd057fbbe44c6665ccbc030b729dde
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://patch-diff.githubusercontent.com/wython/wython.github.io/issues/5#start-of-content
https://patch-diff.githubusercontent.com/
Sign in https://patch-diff.githubusercontent.com/login?return_to=https%3A%2F%2Fgithub.com%2Fwython%2Fwython.github.io%2Fissues%2F5
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub SparkBuild and deploy intelligent appshttps://github.com/features/spark
GitHub ModelsManage and compare promptshttps://github.com/features/models
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
GitHub SponsorsFund open source developershttps://github.com/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/accelerator
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://patch-diff.githubusercontent.com/login?return_to=https%3A%2F%2Fgithub.com%2Fwython%2Fwython.github.io%2Fissues%2F5
Sign up https://patch-diff.githubusercontent.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=wython%2Fwython.github.io
Reloadhttps://patch-diff.githubusercontent.com/wython/wython.github.io/issues/5
Reloadhttps://patch-diff.githubusercontent.com/wython/wython.github.io/issues/5
Reloadhttps://patch-diff.githubusercontent.com/wython/wython.github.io/issues/5
wython https://patch-diff.githubusercontent.com/wython
wython.github.iohttps://patch-diff.githubusercontent.com/wython/wython.github.io
Notifications https://patch-diff.githubusercontent.com/login?return_to=%2Fwython%2Fwython.github.io
Fork 0 https://patch-diff.githubusercontent.com/login?return_to=%2Fwython%2Fwython.github.io
Star 10 https://patch-diff.githubusercontent.com/login?return_to=%2Fwython%2Fwython.github.io
Code https://patch-diff.githubusercontent.com/wython/wython.github.io
Issues 14 https://patch-diff.githubusercontent.com/wython/wython.github.io/issues
Pull requests 0 https://patch-diff.githubusercontent.com/wython/wython.github.io/pulls
Actions https://patch-diff.githubusercontent.com/wython/wython.github.io/actions
Projects 0 https://patch-diff.githubusercontent.com/wython/wython.github.io/projects
Security 0 https://patch-diff.githubusercontent.com/wython/wython.github.io/security
Insights https://patch-diff.githubusercontent.com/wython/wython.github.io/pulse
Code https://patch-diff.githubusercontent.com/wython/wython.github.io
Issues https://patch-diff.githubusercontent.com/wython/wython.github.io/issues
Pull requests https://patch-diff.githubusercontent.com/wython/wython.github.io/pulls
Actions https://patch-diff.githubusercontent.com/wython/wython.github.io/actions
Projects https://patch-diff.githubusercontent.com/wython/wython.github.io/projects
Security https://patch-diff.githubusercontent.com/wython/wython.github.io/security
Insights https://patch-diff.githubusercontent.com/wython/wython.github.io/pulse
New issuehttps://patch-diff.githubusercontent.com/login?return_to=https://github.com/wython/wython.github.io/issues/5
New issuehttps://patch-diff.githubusercontent.com/login?return_to=https://github.com/wython/wython.github.io/issues/5
谈js继承https://patch-diff.githubusercontent.com/wython/wython.github.io/issues/5#top
javascripthttps://github.com/wython/wython.github.io/issues?q=state%3Aopen%20label%3A%22javascript%22
https://github.com/wython
https://github.com/wython
wythonhttps://github.com/wython
on Jul 19, 2019https://github.com/wython/wython.github.io/issues/5#issue-470209644
javascripthttps://github.com/wython/wython.github.io/issues?q=state%3Aopen%20label%3A%22javascript%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.