prototype属性指向原型对象constructor 的属性,指回与之关联的构造函数// 定义 Person 构造函数
function Person() {
this.name = 'CoderBin'
}
// 给 Person 的原型上添加 getPersonValue 方法(原型方法)
Person.prototype.getPersonValue = function() {
return this.name
}
// 定义 Student 构造函数
function Student() {
this.sno = '001'
}
// 继承 Person — 将 Peson 的实例赋值给 Student 的原型
Student.prototype = new Person()
Student.prototype.getStudentValue = function() {
return this.sno
}
// 实例化 Student
let stu = new Student()
console.log(stu.getPersonValue()) // CoderBin
Student.prototype 实现了对 Person 的继承。
这个赋值重写了 Student 最初的原型,将其替换为 Person 的实例。这意味着 Person 实例可以访问的所有属性和方法也会存在于Student.prototype。这样实现继承之后,代码紧接着又给Student.prototype,也就是这个 Person 的实例添加了 一个新方法。最后又创建了 Student 的实例并调用了它继承的getPersonValue()方法。
下图展示了子类的实例与两个构造函数及其对应的原型之间的关系:
Student.prototype,而Student.prototype(作为 Person 的实例又通过内部的 [[Prototype]] )指向Person.prototype。
注意1:getPersonValue() 方法还在Person.prototype对象上,而 name 属性则在Student.prototype上。这是因为 getPersonValue() 是一个原型方法,而 name 是一个实例属性。Student.prototype现在是 Person 的一个实例,因此 name 才会存储在它上面。
注意2:由于 Student.prototype 的 constructor 属性被重写为指向 Person,所以 stu.constructor 也指向 Person 。
Object.prototype。这也是为什么自定义类型能够继承包括 toString() 、valueOf() 在内的所有默认方法的原因。因此前面的例子还有额外一层继承关系。
下图展示了完整的原型链。
Student 继承 Person ,而 Person 继承 Object 。在调用 stu.toString() 时,实际上调用的是保存在 Object.prototype 上的方法。
instanceof操作符,如果一个实例的原型链中出现过相应的构造函数,则instanceof返回 true 。如下例所示:
console.log(stu instanceof Object) // true
console.log(stu instanceof Person) // true
console.log(stu instanceof Student) // true
从技术上讲,stu 是 Object、Person 和 Student 的实例,因为 stu 的原型链中包含这些构造函数的原型。结果就是 instanceof 对所有这些构造函数都返回 true 。
isPrototypeOf()方法。原型链中的每个原型都可以调用这个方法,如下例所示,只要原型链中包含这个原型,这个方法就返回 true 。
console.log(Object.prototype.isPrototypeOf(stu)) // true
console.log(Person.prototype.isPrototypeOf(stu)) // true
console.log(Student.prototype.isPrototypeOf(stu)) // true
// 定义 Person 构造函数
function Person() {
this.name = 'CoderBin'
}
// 给 Person 的原型上添加 getPersonValue 方法(原型方法)
Person.prototype.getPersonValue = function() {
return this.name
}
// 定义 Student 构造函数
function Student() {
this.sno = '001'
}
// 继承 Person
Student.prototype = new Person()
// 新方法 —— 1
Student.prototype.getStudentValue = function() {
return this.sno
}
// 覆盖已有的方法 —— 2
Student.prototype.getPersonValue = function() {
return 'Bin'
}
// 实例化 Student
let stu = new Student()
console.log(stu.getPersonValue()) // Bin
在上面的代码中,注释1、2的部分涉及两个方法。
// 定义 Person 构造函数
function Person() {
this.name = 'CoderBin'
}
// 给 Person 的原型上添加 getPersonValue 方法(原型方法)
Person.prototype.getPersonValue = function() {
return this.name
}
// 定义 Student 构造函数
function Student() {
this.sno = '001'
}
// 继承 Person
Student.prototype = new Person()
// 通过对象字面量添加新方法,这会导致上一行无效!!!
Student.prototype = {
getStudentValue() {
return this.sno
},
someOtherMethod() {
return 'something'
}
}
// 实例化 Student
let stu = new Student()
console.log(stu.getPersonValue()) // TypeError: stu.getPersonValue is not a function
在这段代码中,子类的原型在被赋值为 Person 的实例后,又被一个对象字面量覆盖了。覆盖后的原型是一个Object 的实例,而不再是 Person 的实例。因此之前的原型链就断了。Student 和 Person 之间也没有关系了。
在使用原型实现继承时,原型实际上变成了另一个类型的实例【1】。这意味着原先的实例属性摇身一变成为了原型属性。下面的例子揭示了这个问题:
// 定义 Person 构造函数
function Person() {
this.letters = ['a', 'b', 'c']
}
// 定义 Student 构造函数
function Student() {
this.sno = '001'
}
// 继承 Person
Student.prototype = new Person()
let stu1 = new Student()
let stu2 = new Student()
stu1.letters.push('d')
console.log(stu1.letters) // ['a', 'b', 'c', 'd']
console.log(stu2.letters) // ['a', 'b', 'c', 'd']
代码解析: 在这个例子中,Person 构造函数定义了一个 letters 属性,其中包含一个数组(引用值)。每个 Person 的实例都会有自己的 letters 属性,包含自己的数组。但是,当 Student 通过原型继承 Person 后,Student.prototype变成了 Person 的一个实例,因而也获得了自己的 letters 属性。这类似于创建了Student.prototype.letters 属性。最终结果是,Student 的所有实例都会共享这个 letters 属性。这一点通过 stu1.letters 上的修改也能反映到 stu2.letters 上就可以看出来。
原型链的第二个问题是,子类型在实例化时不能给父类型的构造函数传参【2】。事实上,我们无法在不影响所有对象实例的情况下把参数传进父类的构造函数。再加上之前提到的原型中包含引用值的问题,就导致原型链基本不会被单独使用。
apply()和call()方法以新创建的对象为上下文执 行构造函数。来看下面的例子:
// 定义 Person 构造函数
function Person() {
this.letters = ['a', 'b', 'c']
}
// 定义 Student 构造函数
function Student() {
// 继承 Person — 使用 call() 方法调用 Person 构造函数
Person.call(this)
}
let stu1 = new Student()
let stu2 = new Student()
stu1.letters.push('d')
console.log(stu1.letters) // ['a', 'b', 'c', 'd']
console.log(stu2.letters) // ['a', 'b', 'c']
代码解析: 示例中继承 Person 那一行代码展示了盗用构造函数的调用。通过使用call() (或 apply() )方法,Person 构造函数在为 Student 的实例创建的新对象的上下文中执行了。这相当于新的 Student 对象上运行了 Person() 函数中的所有初始化代码。结果就是每个实例都会有自己的 letters 属性。
// 定义 Person 构造函数
function Person(name) {
this.name = name
}
// 定义 Student 构造函数
function Student(name) {
// 继承 Person
Person.call(this, name)
// 实例属性
this.age = 18
}
let stu = new Student('CoderBin')
console.log(stu.name) // CoderBin
console.log(stu.age) // 18
代码解析:在这个例子中,Person 构造函数接收一个参数 name ,然后将它赋值给一个属性。在 Student 构造函数中调用 Person 构造函数时传入这个参数,实际上会在 Student 的实例上定义 name 属性。为确保 Person 构造函数不会覆盖 Student 定义的属性,可以在调用父类构造函数之后再给子类实例添加额外的属性。
// 定义 Person 构造函数
function Person(name) {
this.name = name
this.letters = ['a', 'b', 'c']
}
// 在 Person 的原型上添加 sayName 方法
Person.prototype.sayName = function() {
console.log(this.name + ' 你好~')
}
// 定义 Student 构造函数
function Student(name, age) {
// 继承属性
Person.call(this, name)
this.age = age
}
// 继承方法
Student.prototype = new Person()
// 在 Student 的原型上添加 sayAge 方法
Student.prototype.sayAge = function() {
console.log(this.age)
}
let stu1 = new Student('CoderBin', 18)
let stu2 = new Student('Bin', 23)
stu1.letters.push('d')
// 输出 stu1 的信息
console.log(stu1.letters) // [ 'a', 'b', 'c', 'd' ]
stu1.sayName() // CoderBin 你好~
stu1.sayAge() // 18
// 输出 stu2 的信息
console.log(stu2.letters) // [ 'a', 'b', 'c']
stu2.sayName() // Bin 你好~
stu2.sayAge() // 23
代码解析:在这个例子中,Person 构造函数定义了两个属性,name 和 letters ,而它的原型上也定义了一个方法叫 sayName() 。Student 构造函数调用了 Person 构造函数,传入了 name 参数,然后又定义了自己的属性 age 。
此外,Student.prototype 也被赋值为 Person 的实例。 原型赋值之后,又在这个原型上添加了新方法sayAge() 。这样,就可以创建两个 Student 实例,让这两个实例都有自己的属性,包括 letters , 同时还共享相同的方法。
最后:组合继承弥补了原型链和盗用构造函数的不足,是 JavaScript 中使用最多的继承模式。而且组合继承也保留了instanceof操作符和isPrototypeOf()方法识别合成对象的能力。
function object(o) {
function F() {}
F.prototype = o
return new F()
}
这个object() 函数会创建一个临时构造函数,将传入的对象赋值给这个构造函数的原型,然后返回这个临时类型的一个实例。
function object(o) {
function F() {}
F.prototype = o
return new F()
}
let person = {
name: 'CoderBin',
letters: ['a', 'b', 'c']
}
let p1 = object(person)
let p2 = object(person)
p1.name = 'p1'
p1.letters.push('d')
p2.name = 'p2'
p2.letters.push('e')
console.log(person.letters) // [ 'a', 'b', 'c', 'd', 'e' ]
代码解析:在这个例子中,person 对象定义了另一个对象也应该共享的信息,把它传给 object() 之后会返回一个新对象。这个新对象的原型是 person ,意味着它的原型上既有原始值属性又有引用值属性。这也意味着 person.letters 不仅是 person 的属性,也会跟 p1 和 p2 共享。这里实际上克隆了两个 person 。
Crockford推荐的原型式继承适用于这种情况:你有一个对象,想在它的基础上再创建一个新对象。你需要把这个对象先传给 object() ,然后再对返回的对象进行适当修改。
Object.create()方法将原型式继承的概念规范化了。这个方法接收两个参数:作为新对象原型的对象,以及给新对象定义额外属性的对象(第二个可选)。在只有一个参数时,Object.create() 与这里的object()方法效果相同:
let person = {
name: 'CoderBin',
letters: ['a', 'b', 'c']
}
let p1 = Object.create(person)
let p2 = Object.create(person)
p1.name = 'p1'
p1.letters.push('d')
p2.name = 'p2'
p2.letters.push('e')
console.log(person.letters) // [ 'a', 'b', 'c', 'd', 'e' ]
Object.create()的第二个参数与Object.defineProperties()的第二个参数一样:每个新增属性都通过各自的描述符来描述。以这种方式添加的属性会遮蔽原型对象上的同名属性。比如:
let person = {
name: 'CoderBin',
letters: ['a', 'b', 'c']
}
let p1 = Object.create(person, {
name: {
value: 'CoderBin'
}
})
console.log(p1.name)
原型式继承非常适合不需要单独创建构造函数,但仍然需要在对象间共享信息的场合。但要记住,属性中包含的引用值始终会在相关对象间共享,跟使用原型模式是一样的。
function inheritPrototype(o) {
let clone = Object.create(o) // 通过调用函数创建一个新对象
clone.sayHi = function() { // 以某种方式增强这个对象
console.log('Hi~')
}
return clone // 返回这个对象
}
代码解析:在这段代码中,inheritPrototype() 函数接收一个参数,就是新对象的基准对象。这个对象 o 会被传给Object.create()函数,然后将返回的新对象赋值给 clone 。接着给 clone 对象添加一个新方法 sayHi() 。最后返回这个对象。可以像下面这样使用 inheritPrototype() 函数:
let person = {
name: 'CoderBin',
letters: ['a', 'b', 'c']
}
let p1 = inheritPrototype(person)
p1.sayHi() // Hi~
代码解析:这个例子基于 person 对象返回了一个新对象。新返回的 p1 对象具有 person 的所有属性和方法,还有一个新方法叫 sayHi() 。寄生式继承同样适合主要关注对象,而不在乎类型和构造函数的场景。Object.create()函数不是寄生式继承所必需的,任何返回新对象的函数都可以在这里使用。
注意: 通过寄生式继承给对象添加函数会导致函数难以重用,与构造函数模式类似。
// 定义 Person 构造函数
function Person(name) {
this.name = name
this.letters = ['a', 'b', 'c']
}
// 在 Person 的原型上添加 sayName 方法
Person.prototype.sayName = function() {
console.log(this.name)
}
// 定义 Student 构造函数
function Student(name, age) {
Person.call(this, name) // 第一次调用 Person()
this.age = age
}
Student.prototype = new Person() // 第二次调用 Person()
// 让 Student 的原型指回 Student
Student.prototype.constructor = Student
// 在 Student 的原型上添加 sayAge 方法
Student.prototype.sayAge = function() {
console.log(this.age)
}
let stu = new Student('CoderBin', 18)
console.log(stu)
// 输出:Student { name: 'CoderBin', letters: [ 'a', 'b', 'c' ], age: 18 }
console.log(Student.prototype)
// 输出:
// Person {
// name: undefined,
// letters: [ 'a', 'b', 'c' ],
// constructor: [Function: Student],
// sayAge: [Function (anonymous)]
// }
代码解析:代码中注释的部分是调用 Person 构造函数的地方。在上面的代码执行后,Student.prototype上会有两个属性:name 和 letters 。它们都是 Person 的实例属性,但现在成为了 Student 的原型属性。在调用 Student 构造函数时,也会调用 Person 构造函数,这一次会在新对象上创建实例属性 name 和 letters 。这两个实例属性会遮蔽原型上同名的属性。
所以,执行完上面的代码后,有两组 name 和 letters 属性:一组在实例上,另一组在 Student 的原型上。这是调用两次 Person 构造函数的结果。
function inheritPrototype(subType, superType) {
let prototype = Object.create(superType.prototype) // 创建对象
prototype.constructor = subType // 增强对象
subType.prototype = prototype // 赋值对象
}
代码解析:这个 inheritPrototype() 函数实现了寄生式组合继承的核心逻辑。这个函数接收两个参数:子类构造函数和父类构造函数。在这个函数内部,第一步是创建父类原型的一个副本。然后,给返回的prototype 对象设置 constructor 属性,解决由于重写原型导致默认 constructor 丢失的问题。最后将新创建的对象赋值给子类型的原型。如下例所示,调用 inheritPrototype() 就可以实现前面例子中的子类型原型赋值:
// 定义 Person 构造函数
function Person(name) {
this.name = name
this.letters = ['a', 'b', 'c']
}
// 在 Person 的原型上添加 sayName 方法
Person.prototype.sayName = function() {
console.log(this.name)
}
// 定义 Student 构造函数
function Student(name, age) {
Person.call(this, name)
this.age = age
}
// 调用 inheritPrototype() 函数,传入 子类构造函数 和 父类构造函数
inheritPrototype(Student, Person)
// 在 Person 的原型上添加 sayAge 方法
Student.prototype.sayAge = function() {
console.log(this.age)
}
let stu = new Student('CoderBin', 18)
console.log(stu)
// 输出:Student { name: 'CoderBin', letters: [ 'a', 'b', 'c' ], age: 18 }
console.log(Student.prototype)
// 输出
// Person {
// constructor: [Function: Student],
// sayAge: [Function (anonymous)]
// }
这里只调用了一次 Person 构造函数,避免了Student.prototype上不必要也用不到的属性,因此可以说这个例子的效率更高。而且,原型链仍然保持不变,因此instanceof操作符和isPrototypeOf()方法正常有效。寄生式组合继承可以算是引用类型继承的最佳模式。
每文一句:学如逆水行舟,不进则退。本次的分享就到这里,如果本章内容对你有所帮助的话欢迎点赞+收藏。文章有不对的地方欢迎指出,有任何疑问都可以在评论区留言。希望大家都能够有所收获,大家一起探讨、进步!
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案
我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby1.9+ 关于ruby-主要:Objectwhenrun
我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2