请大家指点一个 javaScript 继承代码,代码如下

2016-04-27 15:23:08 +08:00
 palmers
function Person() {
	this.sname = '测试' ;
	this.age = 23 ;
	this.sex = '男' ;
	Person.prototype.say = function() {
		return this.sname + ' , ' + this.age + ' , ' + this.sex ;
	} ;
}


function Student() {

	Student.prototype = new Person() ;
	Student.prototype.constructor = Student ;
	this.school = 'xxx 大学' ;
}

var stu = new Student() ;
alert(stu.__proto__) ;
alert(stu.sname) ; //undefined

为什么stu 没有继承Person 的属性呢? 只能访问自己的。 Student 的原型是[object Object], 请大家指点!谢谢大家!

3014 次点击
所在节点    程序员
23 条回复
xcodebuild
2016-04-28 10:11:01 +08:00
这种写法即使写对了也有很大的隐患,例如下面的代码

function Person() {
this.accounts = []
}

function Student() {
}

Student.prototype = new Person()

var a = new Student()
var b = new Student()

a.accounts.push({github: 'https://github.com/IAmA'})

console.log(b.accounts[0].github) // "https://github.com/IAmA"

对 a 的原型链上的引用变量进行操作时同时改变了 b 的原型链上的值
SmiteChow
2016-04-28 11:49:19 +08:00
@palmers 是的,主要是为了抹平 new Person() 和 直接写 Person() 的差别,要不然
Person() 只是普通的函数调用
new 出来的东西才是真正意义上的 instance

显示 gist 是 V 站自带的功能
palmers
2016-04-28 20:39:21 +08:00
@SmiteChow thank you 非常感谢!!!!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/274805

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX